本质上我想要一个模板类,它有一个数组,其大小是一个模板参数,以保存不变的内容。
类似于:
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});
最佳答案
发布- DR1591内置数组边界现在可以从 braced-init-list 中推导出来,所以:
template<size_t S> struct Baz {
const array<int,S> qux;
Baz(const array<int,S>&par) : qux(par) {
cout << "size is " << S << endl;
}
Baz(const int (&par)[S]) : qux(std::experimental::to_array(par)) {}
};
template<size_t S> Baz<S>
GetBaz(const int (&in)[S]) {
return Baz<S>(in);
}
std::experimental::to_array
从一个内置的创建一个 std::array
。请参阅链接的 cppreference 页面以了解实现情况。
你可以一直使用内置数组,但它有点烦人:
template<size_t S> struct Baz {
const int bar[S];
template<size_t... Is>
Baz(const int (&par)[S], std::index_sequence<Is...>)
: bar { par[Is]... } {}
Baz(const int (&par)[S]) : Baz(par, std::make_index_sequence<S>()) {}
};
template<size_t S> Baz<S>
GetBaz(const int (&in)[S]) {
return Baz<S>(in);
}
关于c++ - 如何从构造函数参数初始化模板成员数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233587/