Can we use static data members in class template




















Victor Bazarov. It's not wrong. You're using a compiler that is at least five years old. Change your compiler. Thank You very much. Gianni Mariani. Alibek wrote: Thank You very much. Don't waste your time, get the GCC 3. This discussion thread is closed Start new discussion.

Instantiation of static variable in template class fails, why?? Protected Static may as well be public? Peterson last post: by. In the class constructor, we increment the counter and we decrement that in desctructor. But handling static members in template class is little bit tricky. Now if we want to maintain how many objects are created out of this class, we can have a static counter in the class. We have another static function, printObjectCount , to print the counter.

So far so good. Now consider another code snippet. Here we created 6 objects. The output of the program is like this. This might appear strange. Why to maintain multiple static variables when the class is one and static variables are class specific. Because the assumption that we have only class is not true.

First, we create five objects from our template class — three ints, one char and one float. The ints, which are all the same type, share the static variable count.

Each time an int template class is created, count is incremented. The float and the char objects have their own static variable count because they are different types.

If you were to create more char and float objects, count would increase for those particular types too.



0コメント

  • 1000 / 1000