Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading