0

我写了一个类,它有两个组件,一个随机类类型 T 和一个整数,我实现它如下: 在 Test.h 中像:

    template <class A, int B>class Test { // two components, 
    private: 
        A first;
        int second;

    public:
        Test();
        Test (A,int);
    }

在 Test.cpp 我做了:

    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;}

但是在主要功能中:

    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

如何从上述泛型类声明对象实例?

4

2 回答 2

0

You forgot the semicolon at the end of the class template definition.

于 2012-04-05T00:01:43.050 回答
0
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.

于 2012-04-05T00:03:51.910 回答