简体   繁体   中英

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) > ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM