Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template Class with Static Members - Same for all types of the class

If you have a template class with a static variable, is there any way to get the variable to be the same across all types of the class, rather than for each one?

At the moment my code is like this:

 template <typename T> class templateClass{
 public:
     static int numberAlive;
     templateClass(){ this->numberAlive++; }
     ~templateClass(){ this->numberAlive--; }
};

template <typename T> int templateClass<T>::numberAlive = 0;

And main:

templateClass<int> t1;
templateClass<int> t2;
templateClass<bool> t3;

cout << "T1: " << t1.numberAlive << endl;
cout << "T2: " << t2.numberAlive << endl;
cout << "T3: " << t3.numberAlive << endl;

This outputs:

 T1: 2
 T2: 2
 T3: 1

Where as the desired behaviour is:

 T1: 3
 T2: 3
 T3: 3

I guess I could do it with some sort of global int that any type of this class increments and decrements, but that doesnt seem very logical, or Object-Oriented

Thank you anyone who can help me implement this.

like image 698
jtedit Avatar asked Apr 05 '12 22:04

jtedit


People also ask

Can template class have static function?

Yes. The static member is declared or defined inside the template< … > class { … } block.

What is the difference between class template and template class?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template. is a template used to generate template classes.

What happens when there is a static member in template?

Static data members and templates (C++ only) The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .

Do static data members belong to all instances of a class?

The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.


1 Answers

Have all the classes derive from a common base class, whose only responsibility is to contain the static member.

class MyBaseClass {
protected:
    static int numberAlive;
};

template <typename T>
class TemplateClass : public MyBaseClass {
public:
    TemplateClass(){ numberAlive++; }
   ~TemplateClass(){ numberAlive--; }
};
like image 74
Oliver Charlesworth Avatar answered Sep 18 '22 14:09

Oliver Charlesworth