Archived

This topic is now archived and is closed to further replies.

stefu

Static template class variable declaration question

Recommended Posts

Question: Why can I put static template class variable declaration to header file, but if I put non-template class static variable declaration there it gives ''multiple definition of...'' error? Sample code:
  

//

// This code in tnttest.h

//


//

// Non-template class with static variable

//

class TestNoTemplate
{
public:
	static int intvalue;
};

// Static variable declaration

int TestNoTemplate::intvalue = 0;

//

// Template class with static variable

//

template<class T> class TestTemplate
{
public:
	static T Tvalue;
};
// Templated static variable declaration

template<class T> T TestTemplate<T>::Tvalue=0;
  
Now I include this header from test1.cpp and test2.cpp. I get link-time error: multiple definition of `TestNoTemplate::intvalue'' I know I have to put the declaration to source-file, not to header file. But how does templates handle this automatically? That''s no problem to me, I''m just interested knowing

Share this post


Link to post
Share on other sites
Template code is created at compile-time as the compiler figures out the types that you are actually going to use. This is one of the reasons why you have to put template definitions/implementations in the same file, because the type is unknown and needs to be "filled in" as the compiler pilfers through your code So when you have multiple instances of a static template variable, it might not really be multiple instances, but instances of different types, which is OK. Also, you can't seperate the inititialization of static member variables from their definition inside the class for the same reason as above, so it would be kinda "unfair" if the compiler gave you errors for multiple definition if the type was the same, because you're forced to keep them together anyway! (don't quote me on that last one, I just like the reasoning )

Non-template static member variables are another story. You have to put them in a source file as opposed to a header file so that they really are only initialized once, otherwise you get that error.

[edited by - Zipster on December 27, 2002 3:31:01 PM]

Share this post


Link to post
Share on other sites
Thank you.

quote:
Original post by Zipster
So when you have multiple instances of a static template variable, it might not really be multiple instances, but instances of different types, which is OK.


I just noticed this and it explains why I can''t get PhysicObjects outside the physics.cpp using template-based autolist!

Share this post


Link to post
Share on other sites
Make it into a static method instead, and replace blabla.Tvalue with blabla.Tvalue().

  
template <class T>
class TestTemplate
{
public:
static T& Tvalue()
{
static T value = 0;
return value;
}
};



Update GameDev.net system time campaign: ''date ddmmHHMMYYYY''

Share this post


Link to post
Share on other sites