推导模板参数以获得初始值设定项列表的大小 [英] Deduce template argument for size of initializer list
问题描述
我有以下(不可编译)代码:
I have the following (not compilable) code:
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
。
Here, I want to pass an arbitrary number of int
s to a function foo
-- for convenience, I will use the std::initializer_list
notation.
I tried to use an std::array
to aggregate the int
s (as shown in the code above), however, the compiler can not deduce the array size since the int
s are passed as an std::initializer_list
.
使用 std :: initializer_list
代替 std :: array
也不能解决问题,因为(与 std :: array
相比) std :: initializer_list
不会被捕获为模板参数。
Using an std::initializer_list
instead of an std::array
also does not solve the problem since (in contrast to std::array
) the size of the std::initializer_list
is not captured as template argument.
有人知道可以使用哪种数据结构,以使 int $可以使用
std :: initializer_list
表示法传递c $ c>,而无需传递模板参数 N
foo
是明确的吗?
Does anyone know which data structure can be used so that the int
s can be passed by using the std::initializer_list
notation and without passing the template argument N
of foo
explicitly?
在此先感谢
推荐答案
感谢核心问题1591 ,您可以使用
template <std::size_t N>
void foo( int const (&arr)[N] )
{
// Code, where "N" is used.
}
foo({1, 2, 3});
这篇关于推导模板参数以获得初始值设定项列表的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!