Is there a way to implement a compile-time type dictionary via C++ templates?
e.g. if I have a number of classes like these:
class ProtocolMajor1Minor2 { ... };
class ProtocolMajor4Minor3 { ... };
...
class ProtocolMajor12Minor21 { ... };
…is there a way to use C++ templates that would allow me to do something like this:
void foo(int majorVersion, int minorVersion)
{
LookupMap<majorVersion,minorVersion>::innertype *specific =
new LookupMap<majorVersion,minorVersion>::innertype;
return specific->FunctionalityFoo();
}
In case it is not clear, LookupMap acts just as the name says: given the two integer parameters (protocol major and minor versions) it is supposed to provide the specific protocol type I need, via the innerType “trait”.
I can’t use the preprocessor to create function “foo” as a macro (using ## or #), for two reasons: (a) it is big, not like in this example, and I don’t want a huge function coded as a macro, and (b) the naming mappings are not direct (i.e. major version A and minor version B do not point to class “ProtocolMajorAMinorB”.
You may also be thinking that “FunctionalityFoo” should be a member of a base type:
you are correct, but this is code generated from legacy code generators, i.e. untouchable.
There are in fact many functions like “FunctionalityFoo” generated for each combination of (major,minor), and I don’t want to create if/then/else ladders for each of them.
I tried template specialization but failed to find a syntax that works.
Is there a way to do it via templates?
No, templates are compile-time construct, so you cannot use variables as template arguments.
For this to work you need to do something like this (i.e. not use runtime-provided variables):