c++ - 推导初始化列表大小的模板参数

标签 c++ c++14 initializer-list template-argument-deduction

我有以下(不可编译)代码:

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符号并且不传递模板参数 Nfoo明确?

提前致谢

最佳答案

感谢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/

相关文章:

c++ - 通过拆分 char 数组创建字符串

c++ - 错误C2664 : 'CSchemaString::CSchemaString(LPCTSTR)' : cannot convert parameter 1 from 'int' to 'LPCTSTR' [closed]

c++ - 在 C++11 或更高版本中,有没有一种方法可以让 constexpr 确定没有 UB 的字节序?

c++ - C++ 中的每个表达式是否都具有非指针类型,如非引用类型

c++ - 在不知道参数的情况下传递模板

c++ - 套接字监听不会在 linux 下的 C++ 中解除绑定(bind)

c++ - 适当提取 vector 内的对象类型,然后在比较中使用。由 小码哥发布于

c++ - 编译时模板 `std::integral_constant` 计数器 - 如何实现它?

c++ - c++11 中 std::initializer_list 的好处

c++ - 为什么存在 C++11 std::initializer_list 构造函数重载规则?