There are a few approaches.
First, if you know the enum
at compile time, you can create a metafunction that takes the enum
as a template argument and return the tyoe as expected.
If you do not, there are a few approaches.
First, you can do a magic switch, where you take a functor and invoke it with the runtime-determined enum
value. Amusingly this is best done by first implementing the above metafunction solution.
A second approach is type erasure. You return an object that is externally uniform, but inside it knows that it has a particular type. As an exampke, boost::variant
. Now accessing that internal tyoe can involve the above solution (boost
visitor like), or maybe a virtual
or std::function
interface that stores the different behavior internally.
Finally, you can use the magic switch technique by mapping the runtime enum
into a compile time enum
(instead of a type) and just use the fist technique.
The magic switch technique is not all that magic. Write a switch statement and in each case invoke a template functor with a type or compile time constant. To make it fancy, take the 'body' of the switch as a template parameter, and maybe even use some metaprogramming to generate the switch code via nested if
or an array lookup. Those advanced techniques are not required.