How to make static Variables in Template classes

N

Nils

Hi,
Ich have a template class and want to initialize a static variable, that is
available for all objekts of the template class, doesn't matter what
template parameter is used.
Can someone please tell me how it will work!

Thanks a lot!
Nils
 
V

Victor Bazarov

Nils said:
Ich have a template class and want to initialize a static variable, that is
available for all objekts of the template class, doesn't matter what
template parameter is used.

You mean, like this:

template<class T> struct NilsClass {
static int someStaticVar;
};

// definition of the static member of the template
template<class T> int NilsClass<T>::someStaticVar = 42;

#include <iostream>
int main() {
NilsClass<double> d;
std::cout << d.someStaticVar << std::endl;
NilsClass<std::eek:stream> dd;
std::cout << dd.someStaticVar << std::endl;
}

Victor
 
N

Nils

Yes, thanks a lot.


Victor Bazarov said:
You mean, like this:

template<class T> struct NilsClass {
static int someStaticVar;
};

// definition of the static member of the template
template<class T> int NilsClass<T>::someStaticVar = 42;

#include <iostream>
int main() {
NilsClass<double> d;
std::cout << d.someStaticVar << std::endl;
NilsClass<std::eek:stream> dd;
std::cout << dd.someStaticVar << std::endl;
}

Victor
 
N

Nicholas Hounsome

Nils said:
Yes, thanks a lot.

Nils / Victor - I think there may be a misunderstanding - in the above
d.someStaticVar is not the same as dd.someStaticVar

If you want the same var for all template instantiations as Nils originally
stated then you put the static in a non-template class and have the template
class derive from that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top