模板循环通过元组

时间:2015-03-25 18:44:12

标签: c++ c++11 variadic-templates stdtuple

我正在使用可变参数模板,我正在尝试为元组实现operator<<

我已经尝试了以下代码,但它没有编译(GCC 4.9 with -std = c ++ 11)。

template<int I, typename ... Tlist>
void print(ostream& s, tuple<Tlist...>& t)
{
    s << get<I>(t) << ", ";
    if(I < sizeof...(Tlist)){
        print<I+1>(s,t);
    }
}
template<typename ... Tlist>
ostream& operator<<(ostream& s, tuple<Tlist...> t)
{
    print<0>(s,t);
    return s;
}

错误信息非常神秘且冗长,但它基本上表示没有匹配函数调用get。有人能解释一下为什么吗? 感谢。

编辑: 这是我正在使用的模板实例

auto t = make_tuple(5,6,true,"aaa");
cout << t << endl;

2 个答案:

答案 0 :(得分:1)

if (blah) {}中的代码已编译,即使条件blah为false,也必须有效。

template<bool b>
using bool_t = std::integral_constant<bool, b>;

template<int I, typename ... Tlist>
void print(std::ostream& s, std::tuple<Tlist...> const& t, std::false_type) {
  // no more printing
}

template<int I, typename ... Tlist>
void print(std::ostream& s, std::tuple<Tlist...> const& t, std::true_type) {
  s << std::get<I>(t) << ", ";
  print<I+1>(s, t, bool_t<((I+1) < sizeof...(Tlist))>{});
}
template<typename ... Tlist>
std::ostream& operator<<(std::ostream& s, std::tuple<Tlist...> const& t)
{
  print<0>(s,t, bool_t<(0 < sizeof...(Tlist))>{});
  return s;
}

应该有效。这里我们使用标签调度来控制递归调用哪个重载:如果true_type是元组的有效索引,则第3个参数为I,如果不是,则为false_type。我们这样做而不是if语句。我们总是递归,但是当我们到达元组的末尾时,我们会进入终止过载。

live example

顺便说一句,如果<<中定义的两种类型的重载std符合标准,那么它是不明确的:它取决于std::tuple<int>是否是“用户定义的类型” ,标准没有定义的条款。

最重要的是,最好的做法是为该类型的命名空间中的类型重载运算符,因此可以通过ADL找到它。但是,在<<内重载std在标准下是非法的(您不能将新的重载注入std)。在某些情况下,结果可能会出现令人惊讶的行为,其中发现了错误的重载,或者找不到过载。

答案 1 :(得分:0)

你必须使用专门化或SFINAE作为分支,即使没有采取生成实例化:

template<int I, typename ... Tlist>
void print(ostream& s, tuple<Tlist...>& t)
{
    s << get<I>(t) << ", ";
    if(I < sizeof...(Tlist)){
        print<I+1>(s,t); // Generated even if I >= sizeof...(Tlist)
    }
}

因此,如果print不会更快地产生错误,您将无限制地get<sizeof...(Tlist)>实例化。

您可以在没有递归的情况下编写它:

template<std::size_t ... Is, typename Tuple>
void print_helper(std::ostream& s, const Tuple& t, std::index_sequence<Is...>)
{
    int dummy[] = { 0, ((s << std::get<Is>(t) << ", "), 0)...};
    (void) dummy; // remove warning for unused var
}


template<typename Tuple>
void print(std::ostream& s, const Tuple& t)
{
    print_helper(s, t, std::make_index_sequence<std::tuple_size<Tuple>::value>());
}

Live example

相关问题