Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Template Class With Static Data Member (http://www.velocityreviews.com/forums/t695540-template-class-with-static-data-member.html)

Immortal Nephi 08-21-2009 04:09 AM

Template Class With Static Data Member
 
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;
}

Alf P. Steinbach 08-21-2009 04:44 AM

Re: Template Class With Static Data Member
 
* 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

Juha Nieminen 08-21-2009 02:57 PM

Re: Template Class With Static Data Member
 
Immortal Nephi wrote:
> 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.


All times are GMT. The time now is 06:52 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.