perencia
perencia

Reputation: 1552

Template handler methods

Suppose I want to have different handlers for different kind of messages, each message is identified by an int. I want to define each handler as an instantiation of a template method.

The idea is something like this:

handlers.h

enum Handler {
    MESSAGE1,
    MESSAGE2
};

template<MESSAGE1>
void handle() {
}

main.cpp

int main()
{
    handle<Handler::MESSAGE>();
}

Of course this code does not compile because MESSAGE1 is not a type. So, how could I create a different type for each message ? Also, I'd like to maintain the use of these types as meaningful as possible (hence the use of enums).

Upvotes: 1

Views: 398

Answers (2)

Barry
Barry

Reputation: 303457

You can use std::integral_constant (or write your own empty type wrapper to do the same thing) to wrap your enums into types:

template <Handler H>
using handle_t = std::integral_constant<Handler, H>;

And then overload on different types:

void handle(handle_t<MESSAGE1> ) { ... }
void handle(handle_t<MESSAGE2> ) { ... }

which you can call via:

handle(handle_t<MESSAGE1>{} );

Upvotes: 2

Cameron
Cameron

Reputation: 98826

You want what's called non-type template parameters with template specialization:

template<Handlers H> void handle();  // default

template<> void handle<MESSAGE1>() {
    // ...
}

template<> void handle<MESSAGE2>() {
    // ...
}

Upvotes: 5

Related Questions