C++11 可变模板 : default index array value

标签 c++ c++11 tuples variadic-templates

这是一个使用改编自 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/

相关文章:

c++ - 在 C++11 中,使用 std::unique_lock<std::mutex> 作为类成员是否明智(甚至安全)?如果是这样,是否有任何指导方针?

c++ - 使用 static_cast 转换 POD 对象

c++ - 将数组数据插入模板

C++ vector 初始化

c++ - 在递归函数中创建 std::list of value 而不是 std::list of pointers

python - 将字典转换为元组列表

python - 如果元组不包含 __iadd__ 但仍使用 INPLACE_ADD 指令,则就地添加如何在元组中工作?

c++ - 多个隐式转换运算符

C++ 闭包和 std::function

c++ - 使用可变参数模板计算元组大小时大小错误