0

ランダム クラス タイプ T と整数の 2 つのコンポーネントを取るクラスを作成し、次のように実装します。

    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

クラス テンプレート定義の末尾にあるセミコロンを忘れました。

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

これら 2 つのテンプレート関数定義は.cpp、宣言だけでなく、これらの関数を呼び出すすべてのコンパイル ユニットで実際のコードを使用できるようにする必要があります。

Test<int, int >  T1; //It can not be passed

これは無効です。2 番目intはタイプですが、テンプレートはint値を期待しています

Test<int, 4> T2; //It can not be passed 

これで何も問題はありません

int x = 8;
Test<int, x> T3 (3,4);// can not be passed

テンプレート パラメータとして使用できるようにするには、これらの行の最初の行をstatic const x = 8作成する (つまりx、コンパイル時の定数を作成する) 必要があります。

また、クラス定義の最後にセミコロンがありません。

于 2012-04-05T00:03:51.910 に答える