0

ねえ、式パラメーターを使用してテンプレート クラス定義を「オーバーロード」できるかどうかを調べようとしています。次のコード スニペットのようなものです。

template<class T>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = 5;
        cout << "Testvar: " << testvar << endl;
    }
};

template<class T>
class Test<T, int num>
{
public:
    T testvar;

    Test()
    {
        testvar = 10;

        cout << "Testvar: " << testvar << endl;
        cout << "Param: " << num << endl;
    }
};

ありがとう。

編集:記録のために、それが明らかでない場合、私はC ++でこれをやろうとしています... :)

4

2 に答える 2

2

テンプレートは、探しているものに似たものを提供できるデフォルトのテンプレート パラメーターを許可します。

template<class T, int num = -1>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = (num == -1 ? 10 : 5);

        cout << "Testvar: " << testvar << endl;
        if ( num != -1 )
            cout << "Param: " << num << endl;
    }
};
于 2009-05-26T04:16:01.770 に答える
1

のテンプレート引数を 1 つだけ指定できるようにしたい場合は、 Shmoopty が示唆Testするように、デフォルトのテンプレート パラメータを宣言する必要があります。

さまざまなパラメーター値に部分的に特化することもできます。

// This base template will be used whenever the second parameter is
// supplied and is not -1.
template<class T, int num = -1>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = 10;
        cout << "Testvar: " << testvar << endl;
        cout << "Param: " << num << endl;
    }
};

// This partial specialisation will be chosen
// when the second parameter is omitted (or is supplied as -1).
template<class T, int num>
class Test<T, -1>
{
public:
    T testvar;

    Test()
    {
        testvar = 5;
        cout << "Testvar: " << testvar << endl;
    }
};

ifこれによりorステートメントが不要にswitchなり、わずかに高速になり (実行時テストは実行されません)、追加の部分的な特殊化の形で後で追加のケースを「移植」することができます。(どちらのアプローチがより明確かは、個人の好みの問題です。)

于 2009-05-26T12:33:05.007 に答える