Bar*_*rry 7 c++ variadic-templates c++11
我想编写一个类方法,它接受一个模板参数包,但是零参数,并对类型进行"迭代":
struct Bar {
template <typename T, typename... Ts>
void foo() {
// something with T that involves Bar's members
foo<Ts...>();
}
};
Run Code Online (Sandbox Code Playgroud)
实现这个的首选方法是什么?
您可以使用以下内容:
struct Bar {
template <typename... Ts>
void foo() {
int dummy[] = {0 /*Manage case where Ts is empty*/,
(bar<Ts>(), void() /* To avoid overload `operator,` */, 0)...};
(void) dummy; // suppress warning for unused variable.
}
template <typename T>
void bar()
{
// something with T that involves Bar's members
}
};
Run Code Online (Sandbox Code Playgroud)
在C++17中,可以用Folding表达式来简化:
struct Bar {
template <typename... Ts>
void foo() {
(static_cast<void>(bar<Ts>()), ...);
}
template <typename T>
void bar()
{
// something with T that involves Bar's members
}
};
Run Code Online (Sandbox Code Playgroud)