Iterating over C++ variadic template typelist

Viewed 395

Suppose I use a variadic template as typelist:

template <typename ... Types> struct tl {};
using my_list = tl<MyTypeA, MyTypeB, MyTypeC>;

Now I want to invoke a template function for each type, such as:

myFunc<MyTypeA>();
myFunc<MyTypeB>();

How would I accomplish that ?

3 Answers

With C++17, you might use fold expression

template <typename ...Ts>
void call_my_func(my_list<Ts...> )
{
    (myFunc<Ts>(), ...);
}

With c++17 you can use fold expressions.

template <typename ... Types>
void callMyFunc(my_list<Types...>) {
    (myFunc<Types>(), ...);
}

C++11 version:

template <typename ... Types>
void forEachMyFunc(tl<Types...>)
{
    int dummy[] = {
        (myFunc<Types>(), 0)...
    };
    (void)dummy;
}

https://godbolt.org/z/4nK67M

Here is more devious version:

template<typename T>
class MyFunc {
public:
    void operator()() const {
        myFunc<T>();
    }
};

template <template<typename> class F, typename ... Types>
void forEachTypeDo(tl<Types...>)
{
    int dummy[] {
        (F<Types>{}(), 0)...
    };
    (void)dummy;
}
...
forEachTypeDo<MyFunc>(my_list{});
Related