我想创建一个类似于 int
数组构造函数的构造函数:int foo[3] = { 4, 5, 6 };
但我想这样使用它:
MyClass<3> foo = { 4, 5, 6 };
我的类(class)里有一个私有(private)的n
大小的数组:
template<const int n=2>
class MyClass {
public:
// code...
private:
int numbers[n];
// code...
};
最佳答案
您需要一个接受 std::initializer_list
的构造函数参数:
MyClass(std::initializer_list<int> l)
{
...if l.size() != n throw / exit / assert etc....
std::copy(l.begin(), l.end(), &numbers[0]);
}
TemplateRex评论...
You might want to warn that such constructors are very greedy and can easily lead to unwanted behavior. E.g.
MyClass
should not have constructors taking a pair ofint
s.
...并且担心过度活跃的版主可能会删除它,所以这里相对安全。 :-)
关于c++ - 如何为我的类创建数组构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810835/