pedim
pedim

Reputation: 69

Access class template arguments in member function

I'd like to have a HandlerGroup that can wrap a bunch of handlers to be used later. Here's my designed API:

void handler1(Data* d) {}
void handler2(Data* d) {}
void handler3(Data* d) {}

using Handler = std::function<void(Data*)>;

template <typename... Handlers>
struct HandlerGroup {
    void run(Data* data) {
    // ??? how to access variadic handlers defined in template arguments
    // for (handler : Handlers...) handler(data);
    }
}

void driver(Data* data) {
    HandlerGroup<handler1, handler2, handler3>::run(data);
}

Upvotes: 0

Views: 128

Answers (1)

rafix07
rafix07

Reputation: 20918

Since C++17 you should use auto... as template parameters,by this you can instatiate your template with passed pointers to function.

Then you can create in based-range for loop initializer list with unpacked Handler(functionPointer), and just call function wrapper:

using Handler = std::function<void(Data*)>;

template <auto... Handlers>
struct HandlerGroup {
    static void run(Data* data) {
        for (const auto& handler :  {Handler(Handlers)...})
            handler(data);
    }
};

void driver(Data* data) 
{
    HandlerGroup<handler1, handler2, handler3>::run(data);
}

Demo

Upvotes: 1

Related Questions