这是一个使用改编自 Johannes Schaub - litb 答案的代码来打印元组的简短程序。和 Luc Danton .
#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;
}
print 的第二个参数永远是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
这样的函数的第二个参数?
最佳答案
没有,没有。
事实上,这个问题并不局限于可变参数模板,它发生在所有模板函数中:参数的模板类型不能从其默认值推导出来。
template <typename T>
void func(T = 0) {} // expected-note {candidate template ignored:\
couldn't infer template argument 'T'}
int main() {
func(); // expected-error {no matching function for call to 'func'}
}
你需要换档。
最简单的方法是提供一个重载,负责传递第二个参数。毕竟,默认参数只是避免编写转发函数的语法糖。
关于C++11 可变模板 : default index array value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10749078/