Home > Net >  C . What's the best way to initialize multiple static variables in a templated class?
C . What's the best way to initialize multiple static variables in a templated class?

Time:09-11

There are class with multiple static variables, e.g.

    template<class T>
    struct A
    {
    // some code...
        static int i;
        static short s;
        static float f;
        static double d;
    // other static variables
    };

The main way is to use the full template name

template<typename T> 
int A<T>::i = 0;
template<typename T> 
short A<T>::s = 0;
template<typename T> 
float A<T>::f = 0.;
template<typename T> 
double A<T>::d = 0.;
// other inits of static variables

this solution contains a lot of the same code (template<typename T> and A<T>) And if the template has several types, this leads to increase this code, e.g.

struct B<T1, T2, T3, T4>
{
   // some code
   static int i;
   //other static variables
};
...
template<typename T1, typename T2, typename T3, typename T4>
int B<T1, T2, T3, T4>::i = 0;
//other static variable

It looks ok for 1-2 static variables, but if you need more it looks terrible I think about using macros, something like this

#define AStaticInit(TYPE) template<typename T> TYPE A<T>
AStaticInit(int)::i = 0;
AStaticInit(short)::s = 0;
AStaticInit(float)::f = 0.;
AStaticInit(double)::d  = 0.;
// other inits of static variables
#undef TArray

But perhaps there are better options for initializing several static variables in a template class with minimum code?

CodePudding user response:

Make them inline to be able to give them initializers:

    template<class T>
    struct A
    {
    // some code...
        inline static int i = 0;
        inline static short s = 0;
        inline static float f = 0.f;
        inline static double d = 0.;
    // other static variables
    };

CodePudding user response:

Create a base class that doesn't need a template and put all your static variables in it.

    struct Base
    {
    // some code...
        static int i;
        static short s;
        static float f;
        static double d;
    // other static variables
    };

    template<class T>
    struct A : public Base
    {
    // some code...
    };
  • Related