我正在尝试(在编译时)将整数解压缩为可变参数的参数。想法是std::index_sequence
在编译时将这些值打包在数组中或(c ++ 14)中。我尝试使用旧帖子中的一些答案,但是我发现该示例代码对我的水平不可读。
这是一个简单的示例,其中包含我需要在正在编写的代码中尝试实现的功能(在本例中尝试使用)std::make_index_sequence
。我不一定需要使用后者。问题在于序列的值未解压缩为可变参数的参数:
#include <cstdio>
#include <iostream>
#include <utility>
using namespace std;
void print(const int &val){
cout << val << endl;
}
template<typename ...S> void print(const int &val, const S&... others)
{
print(val);
print(others...);
}
template<size_t n> void printNumbers(){
std::make_index_sequence<n> a;
print(a);
}
int main(){
printNumbers<6>();
}
GCC8的输出:
tet.cc: In instantiation of ‘void printNumbers() [with long unsigned int n = 6]’:
tet.cc:25:19: required from here
tet.cc:20:8: error: no matching function for call to ‘print(std::make_index_sequence<6>&)’
print(a);
~~~~~^~~
tet.cc:8:6: note: candidate: ‘void print(const int&)’
void print(const int &val){
^~~~~
tet.cc:8:6: note: no known conversion for argument 1 from ‘std::make_index_sequence<6>’ {aka ‘std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5>’} to ‘const int&’
tet.cc:12:30: note: candidate: ‘template<class ... S> void print(const int&, const S& ...)’
template<typename ...S> void print(const int &val, const S&... others)
^~~~~
tet.cc:12:30: note: template argument deduction/substitution failed:
tet.cc:20:9: note: cannot convert ‘a’ (type ‘std::make_index_sequence<6>’ {aka ‘std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5>’}) to type ‘const int&’
std::make_index_sequence<6>
是以下内容的别名:
std::integer_sequence<std::size_t, 0, 1, 2, 3, 4, 5>
这就是表达式的类型,a
它是函数调用的参数print(a)
。您的print
函数需要单独的值,而不是std::integer_sequence
。
为了使您的实现可行,您应该首先推导索引,然后才将它们用作以下参数print
:
template <std::size_t... Is>
void printNumbers(std::index_sequence<Is...>)
{
print(Is...);
}
template <std::size_t N>
void printNumbers()
{
printNumbers(std::make_index_sequence<N>{});
}
在c ++ 17中,您可以删除中间print
函数,然后说:
template <std::size_t... Is>
void printNumbers(std::index_sequence<Is...>)
{
(print(Is), ...);
}
在c ++ 20中,您既可以创建索引序列,也可以在单个函数中推导其索引:
template <std::size_t N>
void printNumbers()
{
[] <std::size_t... Is> (std::index_sequence<Is...>)
{ (print(Is), ...); }(std::make_index_sequence<N>{});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句