问题
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