Template Class With Static Data Member

I

Immortal Nephi

Can you create two objects of template class so template class can
have its own copy of static data member instead of shared static data
member?

template< typename T >
class Test
{
public:
Test() {}
~Test() {}

static T s_data;
};

template< typename T >
T Stack< T >::s_data = 0;

int main()
{
Test< long int > a;
Test< short int > b;

a.s_data = 1; // OK...Own one copy of static data member
b.s_data = 2; // OK...Own one copy of static data member

Test< long int > c;

c.s_data = 3; // Not OK because static data member is shared by a and
c.

return 0;
}
 
A

Alf P. Steinbach

* Immortal Nephi:
Can you create two objects of template class so template class can
have its own copy of static data member instead of shared static data
member?

template< typename T >
class Test
{
public:
Test() {}
~Test() {}

static T s_data;
};

template< typename T >
T Stack< T >::s_data = 0;

The "Stack<T>::" seems to have escaped from your real code; for the code
presented it should be "Test::".

int main()
{
Test< long int > a;
Test< short int > b;

a.s_data = 1; // OK...Own one copy of static data member
b.s_data = 2; // OK...Own one copy of static data member

Test< long int > c;

c.s_data = 3; // Not OK because static data member is shared by a and
c.

return 0;
}

You have two options: (A) make s_data non-static, or (B) add at least one more
template parameter.

You do not explain what your goal is, but it seems likely that (A) is the best
choice anyway.


Cheers & hth.,

- Alf
 
J

Juha Nieminen

Immortal said:
Test< long int > a;
Test< short int > b;

a.s_data = 1; // OK...Own one copy of static data member
b.s_data = 2; // OK...Own one copy of static data member

Test< long int > c;

c.s_data = 3; // Not OK because static data member is shared by a and

If you want every instance of Test to have its own version of s_data,
that's exactly what non-static members are for.
 

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
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top