c++ - 使用 arg、*和* 作为数组实例化 C++ 模板化类

标签 c++ arrays templates instantiation argument-passing

我有一个 C++ 模板类,它的构造函数有一个默认参数。

它可以用非默认参数实例化,作为数组吗? (如果不是,为什么不呢?)

其中一个有效,但不能同时有效(在 g++ 4.6.3 中):

template <class T> class Cfoo {
  public:
    int x;
    Cfoo(int xarg=42) : x(xarg) {}
};

Cfoo<int> thisWorks[10];
Cfoo<int> thisWorks(43);
Cfoo<int> thisFails(43)[10];
Cfoo<int> thisFails[10](43);
Cfoo<int>[10] thisFails(43);
// (even crazier permutations omitted)

最佳答案

你是对的:你只能默认构造数组中的元素,而你可以将任何你喜欢的参数传递给单个对象构造。

如果你需要一个集合,在 C++98 中你可以使用 std::vector:

std::vector<Cfoo<int> >(10, 43);

关于c++ - 使用 arg、*和* 作为数组实例化 C++ 模板化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18854702/

相关文章:

c++ - Qt 应用程序文本大小在 MacOSX 下不正确

c++ - Xcode 新手,不能使用 cout,只有 std::cout 有效

c++ - 从二进制文件中读取结构并插入 vector/STL::list,然后返回它

c - 如何将格式化字符串附加到数组中?

arrays - 如何生成镜像数字序列

javascript - 计算对象属性的重复数组以生成新数组

C++:使用 dll 导出包装非托管 dll

c++ - 如何推断 C++11 中的模板参数类型?

C++ 模板和静态成员 - header 中的定义

C++基础模板题