-1

我正在使用可变参数模板,目前正在尝试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;
}

错误消息非常神秘且冗长,但它基本上表示没有匹配的函数调用获取。有人可以向我解释为什么吗?谢谢。

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

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

2 回答 2

1

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

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如果I是元组的有效索引,false_type如果不是。我们这样做而不是if声明。我们总是递归,但是当我们到达元组的末尾时,我们递归到终止重载。

活生生的例子

<<顺便说一句,其中定义的两种类型的重载std是否符合标准是模棱两可的:它取决于是否std::tuple<int>是“用户定义的类型”,标准未定义的子句。

最重要的是,在该类型的命名空间内为该类型重载运算符被认为是最佳实践,因此可以通过 ADL 找到它。但是,根据标准,<<内部重载std是非法的(您不能将新的重载注入std)。结果在某些情况下可能会有些令人惊讶的行为,例如发现错误的重载或未找到重载。

于 2015-03-25T18:59:45.943 回答
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)
    }
}

因此,您将无限实例化printifget<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>());
}

活生生的例子

于 2015-03-25T18:57:02.480 回答