Advertisement

initialising static members of template classes

Started by January 17, 2001 10:06 AM
2 comments, last by Yorvik 24 years ago
the following code compiles and works ok. the problem arises when i make 'num' a reference, ie change the line static int x; with static int& x; //notice x is now a reference borland compiler gives redeclaration errors. am i missing somethig obvious here?
    
template<class T>
class Base
{
	/* ... */

public:
	static int num;  //<--this is the line featured above


	void Foo() 
	{
	    cout << num << endl;
	}
};

int x = 4;
float y = 6;

template<> Base<int>::num = x;
template<> Base<float>::num = y;

int main()
{
	Base<int> a;
	Base<float> b;

	a.Foo();
	b.Foo();

	return 0;
}
    
is it possible to get around this? Edited by - Yorvik on January 17, 2001 11:08:41 AM
Don''t put template<> before the definitions of the static vars. Like this:

int& Base::nu = i;
float& Base::num = j;
Advertisement
quote:
Original post by Morbo

Don''t put template<> before the definitions of the static vars. Like this:

int& Base::nu = i;
float& Base::num = j;


I don''t know but that don''t seem right to me.

Isn''t this how it''s supposed to work...?

  template<class T>class Base{	  /* ... */  public:    static type& num;  //<--this is the line featured above       void Foo()    {      cout << num << endl;    }    Base(T& value) { num = value; }};int x = 4;float y = 6;template<class T> Base<T>::num = NULL;int main(){  Base<int> a(&x);  Base<float> b(&y);  a.Foo();  b.Foo();  return 0;}  


I''m by no means an expert, but it seems more likely to me.
AP: the "class T" is not required, the compiler deduces the type from the < int > later on.

Morbo: template<> is required (in bcc5.5 anyway)


anyone have any ideas? if not im gonna have to use #defines, and i REALLY dont want to do that.






Edited by - Yorvik on January 19, 2001 10:12:28 AM

This topic is closed to new replies.

Advertisement