I have templated class, say:
template <int X>
struct Foo {
static int get() {return X;}
};
I can of course explicitly instantiate the version that I want:
template class Foo<1>;
I want to generate an error at compile time if a second explicit instantiation is attempted.
template class Foo<1>;
template class Foo<2>; // How to error here at compile time?
Is this possible?
I suspect this will need to use some "redefinition" trick to get the linker to catch this if compilation is done in multiple translation units. I can't for the life of me figure out if this is possible, or how to do it.
If there is a way to do this, does it work without explicit template instantiation?
Context
I'm writing an entirely static class library to manage some hardware on a microcontroller that I'm using. I want to make it easy to change a compile time parameter (X
) and am therefore using templates. #define
is not acceptable. constexpr
won't work, how would you #include
a dependent source file?
Specifically, I have an init()
function that can only be run a single time and I'm actually using __attribute__((constructor))
to force it to be run for me before main()
. If some other user of the library were to inadvertently instantiate a second instance, bad things would happen.