简体   繁体   中英

How to iterate over Variadic template types (not arguments)?

I am writing a class which expects variable number of template types. I need to call a subscriber for each type but note that there are no actual arguments passed to the 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:

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++14 currently with your generic 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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM