本质上我想要一个模板类,其大小是一个模板参数,以保持不变的内容。如何从构造函数参数初始化模板成员数组?
是这样的:
template<size_t S> struct Foo {
const int bar[S];
Foo(const int(&par)[S]) : bar(par) {
cout << "bar size is " << S << endl;
}
};
auto foo = Foo({1,2,3});
我一直在寻找和摆弄一点,几乎都与中间静态方法实现的解决方法和使用std ::阵列:
template<size_t S> struct Baz {
const array<int,S> qux;
Baz(const array<int,S>&par) : qux(par) {
cout << "size is " << S << endl;
}
};
template<size_t S> Baz<S>
GetBaz(const array<int,S>&in) {
return Baz<S>(in);
}
int main() {
auto sample = GetBaz({1,2,3});
return 0;
}
..这已经是一些样板了,但是std :: array似乎还没有从初始化列表构造出来? :-(
prog.cpp: In function 'int main()':
prog.cpp:27:30: error: no matching function for call to 'GetBaz(<brace-enclosed initializer list>)'
auto sample = GetBaz({1,2,3});
你不能用内置阵列,必须使用'的std :: array' –
对于'自动进样做到这一点= GetBaz({1,2,3});'它失败了,因为你需要指定'GetBaz <5>'或其他。初始化器列表长度不是它们类型的一部分。 –
[这个答案中的代码](http://stackoverflow.com/a/6114359/1505939)可以帮助你解决你的问题,如果你愿意使用'GetBaz(1,2,3)'没有额外的大括号 –