【发布时间】:2016-07-14 00:21:42
【问题描述】:
本质上,我想要一个模板类,其中包含一个大小为模板参数的数组,以保存常量内容。
类似:
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::array 实现的解决方法:
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 -
对于
auto sample = GetBaz({1,2,3});它失败了,因为你需要指定GetBaz<5>或其他。初始化器列表长度不是它们类型的一部分。 -
The code in this answer 可以帮助您解决问题,如果您愿意使用
GetBaz(1,2,3)而不使用额外的大括号
标签: c++ arrays templates c++11 c++14