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

static variables in a template class c++

So, I’m pretty new in the generic programmation and I started the following :

template<class T>
class A
{
public:
  static int m;
}

template<class T>
int A<T>::m;

int main()
{
  A::m = 3; //Cannot compile of course !!
  return 1
}

The idea being to have a member variable that could be shared by all the instances of A, no matter what T we have.

Would there be any way of doing this or do I have to use a global variable instead ?

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

>Solution :

Members of class templates are never shared between specializations of the class template. You should consider a class template to be just that: A template to create classes of similar structure based on different types. For each type T the specialization A<T> is an independent class. The resulting classes are not otherwise related in any way.

If you want to have multiple classes share a static data member, you can put the member in a base class:

struct ABase
{
  static int m;
};

template<class T>
struct A : ABase
{
};

int ABase::m;

int main()
{
  A<int>::m = 3;
  return A<double>::m; // will return 3
}

You still need to specify a type for the template argument though when accessing the member through A, because A itself is not a class that has members at all, it is just a template of which specializations may or may not have the m member inherited from a base. In particular you could add partial specializations or explicit (full) specializations of A which override the definition of A<T> for some types of T, so that A<T>::m is not ABase::m any longer.

Also make sure that this really logically makes sense for your use case. Again, specializations of a class template are as such unrelated types.

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