这是一个简短的程序,用于使用代码根据Johannes Schaub - litb和Luc Danton的答案打印元组。C++ 11可变参数模板:默认索引数组值
#include <iostream>
#include <tuple>
template<int ...>
struct seq { };
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };
template<int ...S>
struct gens<0, S...> {
typedef seq<S...> type;
};
template <int ...S, typename ...T>
void print(const std::tuple<T...> & tup, seq<S...> s) {
int res[] = { (std::cout << std::get<S>(tup) << " ", 0)... };
std::cout << std::endl;
}
int main() {
std::tuple<double, int, char> tup(1.5, 100, 'c');
print(tup, gens<std::tuple_size<decltype(tup)>::value >::type());
return 0;
}
打印的第二个参数将总是始终gens<N>::type()
,其中N
是元组的大小。我试图避开了第二个参数通过提供一个默认参数打印:
template <int ...S, typename ...T>
void print(const std::tuple<T...> & tup, seq<S...> s = gens<std::tuple_size<decltype(tup)>::value >::type()) {
int res[] = { (std::cout << std::get<S>(tup) << " ", 0)... };
std::cout << std::endl;
}
然而,结果是一个编译器错误:
tmp5.cpp: In function ‘void print(const std::tuple<_Elements ...>&, seq) [with int ...S = {}; T = {double, int, char}]’:
tmp5.cpp:23:12: error: incomplete type ‘std::tuple_size&>’ used in nested name specifier
你知道有什么方法可以提供S...
无函数的第二个参数如print
?
铿锵样式的评论真的很讨厌。 –
@ JohannesSchaub-litb:我必须承认,我非常喜欢这种呈现编译错误的方式(当时只有几个人......) –
太糟糕了。我正在处理异构元组(元组,array ,...>',其内容可以全部发送到模板函数'template array f(array )'以产生新的我想现在,我将把序列设置为一个常量表达式,以避免在第二个参数中出现重复的“gens”代码。 –
user