Search code examples
c++templatesc++17variadic-templates

Initializing array with results of variadic class template type's member function?


Say I have a template type ...

template<typename ...Ts>
struct SomeStruct {
    
    std::tuple<Ts...> some_tuple;

}

... where I'm sure any type expanded from Ts all share a base class, and thus some member function that returns some type R.

How could I go about collecting the results of calling that member function on each type in Ts, for example in something like std::array< R, sizeof...(Ts) >?


Solution

  • Given that all Ts... element are supporting a foo() method, returning a R value, I suppose you can use std::apply(), if you can use C++17

    std::apply([](auto ... vals)
               { return std::array<R, sizeof...(vals)>{ vals.foo()... }; },
               some_tuple);
    

    or maybe simply

    std::apply([](auto ... vals)
               { return std::array { vals.foo()... }; },
               some_tuple);
    

    using std::array deduction guides.

    If you can use only C++14, you can emulate std::apply() using std::make_index_sequence/std::index_sequence