constant template type

Mar 20, 2012 at 11:47pm
I'm tring to return a value as const and I keep getting this error
error LNK2001: unresolved external symbol "private: static unsigned char Random<unsigned char>::num" (?num@?$Random@E@@0EA)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template<typename T>
class Random
{
private:
	static T num;
public:
	static const T getnumc()
	{
		return (const T) num;
	}
	static T getnum()
	{
		return num;
	}
	Random<typename T>( T min, T max )
	{
		num = ( ( rand() / ( RAND_MAX + 1 ) ) * ( max - min ) ) + min;
	}
};

What am I doing wrong?
Mar 20, 2012 at 11:53pm
Someone correct me if I'm wrong, but I believe you'll need to instantiate your static variable for the types you are going to instantiate your template class to. The problem here is that you are generated an 'unsigned char' version of this class, but it has this static unsigned char 'num' that the linker can't find an instantiation for.
Mar 21, 2012 at 12:22am
I removed the static from line 5, but now I'm getting this error...
error C2440: 'type cast' : cannot convert from '' to 'unsigned char'

at line 9.

So how can I convert it to a constant of the type?
Mar 21, 2012 at 12:30am
Going back to Zhuge answer - he was talking about something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
template<typename T>
class Random
{
private:
	static T num;
public:
	static const T getnumc()
	{
		return (const T) num;
	}
	static T getnum()
	{
		return num;
	}
	Random( T min, T max )
	{
		num = ( ( rand() / ( RAND_MAX + 1 ) ) * ( max - min ) ) + min;
	}
};


//static member(s)  should have a definition  outside the class
//a generic  definition
template<typename T>
T Random<T>::num;

//An  example  specialisation for floats
template<>
float Random<float>::num = 3.7f;
Last edited on Mar 21, 2012 at 12:31am
Mar 21, 2012 at 12:50am
Thanks, I found more description here
http://msdn.microsoft.com/en-us/library/b1b5y48f.aspx

I have one last question not really related. Why is the random number always the min?
Topic archived. No new replies allowed.