I wrote a class which take two components, an random class type T and an integer, I implement it like following: In Test.h like:
template <class A, int B>class Test { // two components,
private:
A first;
int second;
public:
Test();
Test (A,int);
}
In Test.cpp I did:
template <class T,int i> Test<T,i>::Test() {}
template <class A,int i>Test<A,i>::Test(T a, int b):first(a) {second=b;}
But in Main function:
Test<int, int > T1; //It can not be passed
Test<int, 4> T2; //It can not be passed
int x = 8;
Test<int, x> T3 (3,4);// can not be passed
How I can declare an object instance from the above generic class?
You forgot the semicolon at the end of the class template definition.
template <class T,int i> Test<T,i>::Test() {}
template <class A,int i>Test<A,i>::Test(T a, int b):first(a) {second=b;}
You need to put these two template function definitions in the header rather than the .cpp
- the actual code needs to be made available to all compilation units that call these functions, not just the declaration.
Test<int, int > T1; //It can not be passed
This is invalid, the second int
is a type, but the template expects an int
value
Test<int, 4> T2; //It can not be passed
There's nothing wrong with this
int x = 8;
Test<int, x> T3 (3,4);// can not be passed
You need to make the first of these lines static const x = 8
(i.e. make x
a compile-time constant) to make it a usable as a template parameter
And there's also the missing semicolon at the end of the class definition.
.cpp
file. Updated my answer - je4d 2012-04-05 00:49
Test<int, 4> T2;
could be compiled, but it cased an error when linking - je4d 2012-04-05 00:54