我有以下(不可编译)代码:
template< size_t N >
void foo( std::array<int, N> )
{
// Code, where "N" is used.
}
int main()
{
foo( { 1,2 } );
}
在这里,我想传递任意数量的 int
s 到函数 foo
-- 为方便起见,我将使用 std::initializer_list
符号。
我尝试使用 std::array
聚合 int
s(如上面的代码所示),但是,编译器无法推断出数组大小,因为 int
s 作为 std::initializer_list
传递.
使用 std::initializer_list
而不是 std::array
也没有解决问题,因为(与 std::array
相比) std::initializer_list
的大小未被捕获为模板参数。
有谁知道可以使用哪种数据结构来得到 int
可以使用 std::initializer_list
传递 s符号并且不传递模板参数 N
的 foo
明确?
提前致谢
最佳答案
感谢core issue 1591 , 你可以使用
template <std::size_t N>
void foo( int const (&arr)[N] )
{
// Code, where "N" is used.
}
foo({1, 2, 3});
关于c++ - 推导初始化列表大小的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40241370/