为了账号安全,请及时绑定邮箱和手机立即绑定

漂亮打印std :: tuple

漂亮打印std :: tuple

C++
萧十郎 2019-12-10 13:08:02
这是我先前关于漂亮打印的STL容器的问题的跟进,我们设法为其开发了一个非常优雅且完全通用的解决方案。在下一步中,我想std::tuple<Args...>使用可变参数模板(严格来说是C ++ 11)包括的漂亮打印。对于std::pair<S,T>,我只是说std::ostream & operator<<(std::ostream & o, const std::pair<S,T> & p){  return o << "(" << p.first << ", " << p.second << ")";}打印元组的类似结构是什么?我尝试了各种形式的模板参数堆栈解压缩,传递索引并使用SFINAE来发现何时到达最后一个元素,但是没有成功。我不会因我的密码破译而负担你;希望问题描述很简单。本质上,我想要以下行为:auto a = std::make_tuple(5, "Hello", -0.1);std::cout << a << std::endl; // prints: (5, "Hello", -0.1)奖励积分包括与上一个问题相同的通用水平(char / wchar_t,对定界符)!
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

我在C ++ 11(gcc 4.7)中工作正常。我敢肯定,我没有考虑过一些陷阱,但是我认为代码易于阅读并且并不复杂。唯一奇怪的是可以确保我们在到达最后一个元素时终止的“后卫”结构tuple_printer。另一个奇怪的事情可能是sizeof ...(Types),它返回Types类型包中的类型数。它用于确定最后一个元素的索引(大小...(类型)-1)。


template<typename Type, unsigned N, unsigned Last>

struct tuple_printer {


    static void print(std::ostream& out, const Type& value) {

        out << std::get<N>(value) << ", ";

        tuple_printer<Type, N + 1, Last>::print(out, value);

    }

};


template<typename Type, unsigned N>

struct tuple_printer<Type, N, N> {


    static void print(std::ostream& out, const Type& value) {

        out << std::get<N>(value);

    }


};


template<typename... Types>

std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& value) {

    out << "(";

    tuple_printer<std::tuple<Types...>, 0, sizeof...(Types) - 1>::print(out, value);

    out << ")";

    return out;

}



查看完整回答
反对 回复 2019-12-11
  • 3 回答
  • 0 关注
  • 302 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信