我有一个 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/