如何迭代地打印std :: tuple

时间:2018-04-16 19:00:29

标签: c++ templates metaprogramming

大多数c ++书籍样本利用递归机制来打印std :: tuple。 是否可以通过杠杆sizeof ...(Typename)迭代地打印std :: tuples?

例如,函数签名如下所示:

java.nio.file

然后我可以使用sizeof ...(Ts)知道元组中有多少元素然后 我可以使用std :: get< i>(元组)检索单个元素?

1 个答案:

答案 0 :(得分:1)

这是可能的解决方案之一:

#include <cstddef>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>

template <typename T, std::size_t ...I, typename F>
void tuple_foreach_impl(T &&tuple, std::index_sequence<I...>, F &&func)
{
    // In C++17 we would use a fold expression here, but in C++14 we have to resort to this.
    using dummy_array = int[];
    dummy_array{(void(func(std::get<I>(tuple))), 0)..., 0};
}

template <typename T, typename F> void tuple_foreach(T &&tuple, F &&func)
{
    constexpr int size = std::tuple_size<std::remove_reference_t<T>>::value;
    tuple_foreach_impl(std::forward<T>(tuple), std::make_index_sequence<size>{},
                       std::forward<F>(func));
}

int main()
{
    auto x = std::make_tuple("Meow", 1, 2.3);

    tuple_foreach(x, [](auto &&value)
    {
        std::cout << value << ' ';
    });
    // Prints:
    // Meow
    // 1
    // 2.3
}

使用tuple_foreach制作合适的打印机应该很简单。

template <typename T> void print_tuple(const T &tuple)
{
    std::cout << '{';
    tuple_foreach(tuple, [first = true](auto &value) mutable
    {
        if (!first)
            std::cout << "; ";
        else
            first = 0;
        std::cout << value;
    });
    std::cout << '}';
}

// ...

print_tuple(std::make_tuple("Meow", 1, 2.3)); // Prints `{Meow; 1; 2.3}`