[英]How to iterate over Variadic template types (not arguments)?
I am writing a class which expects variable number of template types.我正在编写一个 class ,它需要可变数量的模板类型。 I need to call a subscriber for each type but note that there are no actual arguments passed to the class.我需要为每种类型调用一个订阅者,但请注意没有实际的 arguments 传递给 class。 Something like:就像是:
template<typename... T>
class Subscriber
{
Subscriber()
{
// for(typename X: T) <-- How to do this?
// {
// PubSub.Subscribe<X>( [](auto data){ // do something with data} );
// }
}
}
In your example, in C++17, you might do:在您的示例中,在 C++17 中,您可以执行以下操作:
template<typename... Ts>
class Subscriber
{
Subscriber()
{
auto f = [](auto data){ /* do something with data*/ };
(PubSub.Subscribe<Ts>(f), ...);
}
}
In C++11/14, you might to use more verbose way, such as:在 C++11/14 中,您可能会使用更详细的方式,例如:
(C++14 currently with your generic lambda) (C++14 目前使用你的通用 lambda)
template<typename... Ts>
class Subscriber
{
Subscriber()
{
auto f = [](auto data){ /* do something with data*/ };
int dummy[] = {0, (PubSub.Subscribe<Ts>(f), void(), 0)...};
static_cast<void>(dummy); // Avoid warning for unused variable.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.