打印std::tuple的N总方式

方式一:递归 + 类模板特化方式

template<typename Tuple, std::size_t N>
struct tuple_printer
{
    static void print(const Tuple& t)
    {
        tuple_printer<Tuple, N - 1>::print(t);
        std::cout << ", " << std::get<N - 1>(t);
    }
};

template<typename Tuple>
struct tuple_printer<Tuple, 1>
{
    static void print(const Tuple& t)
    {
        std::cout << std::get<0>(t);
    }
};

template<typename... Args>
void print_tuple(const std::tuple<Args...>& t)
{
    tuple_printer<decltype(t), sizeof...(Args)>::print(t);
    std::cout << std::endl;
}

方式二:重载<<操作符 + 使用C++14的std::index_senquence

template<typename Char, typename Traits, typename Tuple, std::size_t... Index>
void print_tuple_impl(std::basic_ostream<Char, Traits>& os, const Tuple& t, std::index_sequence<Index...>)
{
    using swallow = int[]; // guaranties left to right order
    (void)swallow { 0, (void(os << (Index == 0 ? "" : ", ") << std::get<Index>(t)), 0)... };
}

template<typename Char, typename Traits, typename... Args>
decltype(auto) operator<<(std::basic_ostream<Char, Traits>& os, const std::tuple<Args...>& t)
{
    os << "(";
    print_tuple_impl(os, t, std::index_sequence_for<Args...>{});
    return os << ")";
}


使用:

std::tuple<int, short, double, char> tp = std::make_tuple(1, 2, 3, 'a');
// 使用方式一
print_tuple(tp);
// 使用方式二
std::cout << tp << std::endl;

posted @ 2016-10-13 11:07  chxuan  阅读(941)  评论(0编辑  收藏  举报