Iterating over C++ variadic template typelist [duplicate]

断了今生、忘了曾经 提交于 2021-02-10 08:05:34

问题


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 ?


回答1:


With c++17 you can use fold expressions.

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



回答2:


With C++17, you might use fold expression

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



回答3:


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{});


来源:https://stackoverflow.com/questions/65215959/iterating-over-c-variadic-template-typelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!