c++ - 终止函数模板递归

标签 c++ templates tuples

我正在尝试为元组创建打印方法。我检查了其他人指定的解决方案,所有这些都使用了一个辅助结构。我不想使用辅助结构。我觉得下面的代码是有效的,但不能把它弄清楚。

#include <iostream>
#include <tr1/tuple>

template<typename tupletype,size_t i>
void print< tupletype ,0>(tupletype t)//error: expected initializer before ‘<’ token
{
    std::cout<<std::tr1::get<0><<" ";
}

template<typename tupletype,size_t i>
void print(tupletype t)
{
    std::cout<<std::tr1::get<i><<" ";// no match for 'operator<<' in 'std::cout << get<-78ul>'(my ide actually hangs here!)
    print<tupletype,i-1>(t);
}

int main (int argc, char * const argv[]) {
    std::tr1::tuple<int,float> a(3,5);
    typedef std::tr1::tuple<int,float> tupletype;
    print<tupletype,0>(a);
}

最佳答案

这是一个没有特定辅助结构的结构:

#include <iostream>
#include <tuple>

template<std::size_t> struct int2type{};

template<class Tuple, std::size_t I>
void print_imp(Tuple const& t, int2type<I>){
  print_imp(t, int2type<I-1>());
  std::cout << ' ' << std::get<I>(t);
}

template<class Tuple>
void print_imp(Tuple const& t, int2type<0>){
  std::cout << std::get<0>(t);
}

template<class Tuple>
void print(Tuple const& t){
  static std::size_t const size = std::tuple_size<Tuple>::value;
  print_imp(t, int2type<size-1>());
}

Live example on Ideone .

关于c++ - 终止函数模板递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992853/

相关文章:

c++ - 在 Visual C++ 6.0 中跟踪变量变化

c++ - 发布 boost::ptr_vector,不匹配文档

python - 如何将 Python 元组转换为 .csv 文件?

c++ - 当整数变量用于在 C++ 中声明数组大小时,错误显示为 "Expression must have a const value"

c++ - 需要 3 个独立的输出

c++ - 每个范围类型的模板特化

Django View 返回在 html 模板中未正确表示的字符串

c++ - 部分模板特化类型折叠规则

python - 删除列表中的元组,然后将平均值分配给删除的元组

python - 如何将字符串的所有排列作为字符串列表(而不是元组列表)?