C ++ Static Variable

I am trying to create only a header library, which, unfortunately, must have a global static variable (either in the class or in the namespace).

Is there a way or preferable solution to have a global static variable while retaining the title design only?

Code here

+5
source share
1 answer

There are several options. The first thing that came to my mind was that C ++ allows the static members of these class templates to define more than one translation unit:

template<class T>
struct dummy {
   static int my_global;
};

template<class T>
int dummy<T>::my_global;

inline int& my_global() {return dummy<void>::my_global;}

The component combines several definitions into one. But only inlinecan also help here, and this solution is much simpler:

inline int& my_global() {
   static int g = 24;
   return g;
}

. ++ , , , . , .

+10

All Articles