1

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

perencia
  • 1,498
  • 3
  • 11
  • 19

2 Answers2

5

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>() {
    // ...
}
Cameron
  • 96,106
  • 25
  • 196
  • 225
2

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>{} );
Barry
  • 286,269
  • 29
  • 621
  • 977