Search code examples
c++templatesapplyvariadic-templatesstdtuple

c++ applying templated function to each element of a tuple


template<typename T>
void print(T& t)
{
    std::cout << t << std::endl;
}

template<typename ... Args>
class Container 
{

    public:

    Container(Args&& ... args)
    : values_(std::forward<Args>(args)...)
    {}

    template<int INDEX>
    typename std::tuple_element<INDEX, std::tuple<Args...> >::type& get()
    {
        return std::get<INDEX>(values_);
    }

    void display()
    {
        // (obviously) does not compile !
        std::apply(print,values_);
    }

    private:
    std::tuple<Args ...> values_;

};

The above code show the intent but is incorrect (where commented), because the function "print" requires a template.

Would there be a way to call the (suitably templated) print function to each element of the tuple values_ ?

run the code : https://onlinegdb.com/SJ78rEibD


Solution

  • You need to unpack the tuple into apply like this:

    void display()
    {
        std::apply([](auto ...ts) { (..., print(ts)); },values_);
    }
    

    Here's a demo.

    Note that this solution uses a fold-expression to make the syntax easier.