I'm working on some library code, and I want users to be able to take advantage of static binding if they are able to. If they are unable to instantiate a class at compile time, I want there to be a dynamic version of the class, so that it can be instantiated at run-time.
For a quick example, say I have a structure template A:
template<bool dynamic, int value=0> struct A
{
static const int Value = value;
};
template<> struct A<true>
{
int Value;
A(int value) : Value(value) {}
};
These definitions allows users of the library to instantiate A statically, and dynamically:
A<true> dynamicA = A<true>(5);
A<false, 5> staticA;
The problem with this method is that I have to write the definition of the class twice. I can think of a few ways of implementing a template that would generate both versions myself, but I can see it becoming a lot of work. Especially for classes that would use varying numbers of parameters, for example:
// It would be much harder to generate a static version of this class,
// though it is possible with type lists. Also, the way I'm imagining it,
// the resulting classes probably wouldn't be very easy to use.
struct A
{
vector<int> Values;
A(vector<int> value) : Values(value) {}
};
Is there a name for this pattern / problem? Is there a meta programming library which has templates which can generate both definitions for me? How do I avoid having to write the definitions of my classes twice?