【发布时间】:2019-04-26 15:45:17
【问题描述】:
我正在尝试(在编译时)将整数解包为可变参数函数的参数。这个想法是在编译时将这些值打包在一个数组或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&’
【问题讨论】:
标签: c++ c++11 c++14 variadic-templates template-meta-programming