Cashif Ilyas
Cashif Ilyas

Reputation: 1705

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

Upvotes: 2

Views: 1086

Answers (1)

Jarod42
Jarod42

Reputation: 217275

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.
    }
}

Upvotes: 6

Related Questions