Search code examples
c++c++11tuplesc++14variadic-templates

access and print data in a tuple and display it using a template function using C++14


i have a list like follows

my_mixed_list = {"Sample String", int_value, user_data_type}

I want to use C++11 std::tuple to display above list in simple white separated way. may be like this:

template <typename T>
    void display_mixed_items (std::tuple <T> mixed) {
         for (const auto& mixed_ele : mixed) std::cout << mixed_ele << " ";
}

I am aware that i would have to overload ostream operator to display the user defined data. But i hope you get the question. I'm not sure why compiler complains about argument list. what is proper way to accomplish above task. couldn't find exact answer on Stackoverflow so to mention.

in Python we could simple use list and tada! But if not tuple is there any other way to this may be using variadic templates or something.


Solution

  • You can get by creating your own for_tuple function to iterate over tuples:

    template<typename T, typename F, std::size_t... S>
    void for_tuple_impl(std::index_sequence<S...>, T&& tup, F& function) {
        using expand_t = int[];
        (void) expand_t{(void(function(std::get<S>(std::forward<T>(tup)))), 0)..., 0};
    }
    
    template<typename T, typename F>
    void for_tuple(T&& tup, F function) {
        for_tuple_impl(
            std::make_index_sequence<std::tuple_size<std::decay_t<T>>::value>{},
            std::forward<T>(tup),
            function
        );
    }
    

    Then use it like this:

    for_tuple(my_tuple, [](auto&& mixed_ele){ std::cout << mixed_ele << ' '; });
    

    C++23 wants to make a language feature called a template for to replace that pile of brakets and parens (not official yet):

    template for (auto&& mixed_ele : mixed) {
        std::cout << mixed_ele << ' ';
    }