简体   繁体   中英

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

There are class with multiple static variables, eg

    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, eg

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?

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
    };

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...
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM