I have a class X…
class X {...}
and I want to have one instance of X for each distinct type of some set of types. (Some of these types are not classes and/or not written by me.)
To do this I thought of:
template<typename T> X& XT();
and then for each type A, B and C:
template<> X& XT<A>() { static X x; return x; }
template<> X& XT<B>() { static X x; return x; }
template<> X& XT<C>() { static X x; return x; }
Will this work? Is this the best way of doing it? What are some alternative ways?
You don’t need to specialize the function. You can simply do this:
And use it as:
All three objects
xa,xbandxcare different instances of X. However,xaandxdare same instances, as they both call the same function.The point here to be noted is that the compiler instantiates different function for each different template argument. So
XT<A>()is a different function thanXT<B>(), and each function has its ownstaticlocal variables. So thestaticlocal variable inXT<A>()is a different instance than the variable inXT<B>().