11

理解できないテンプレート(コンパイラはVisual Studio 2012)に関連するエラーが表示されます。これが本質に要約されたコードです:

// Templated class - generic 
template <typename T>
class Test
{
    public:
        void WorksFine() {} // Comiples and works as expected at runtime
        void Problem();     
};

// Templated class - expicit specialization for T = int.
template <>
class Test<int>
{
        public:
            void WorksFine() {} // Comiples and works as expected at runtime
            void Problem();
};

// The definition below compiles and works fine at runtime.
template<typename T> void Test<T>::Problem() {}


// The definition below gives error C2910.
template<> void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}

WorksFineメソッドの場合、関数定義は明示的に特殊化されたクラス定義内にあり、すべてが正常です。しかし、Problemメソッドの場合、明示的に特殊化されたクラス定義の外部でメソッドを定義すると、エラーC2910が発生します。

どうしてこれなの?エラーC2910は、Test :: Problem()がすでに定義されていることが問題であることを示しています。しかし、それはクラス内で定義されていません...関数定義はなく、宣言だけです。

関数定義をどこに置くかによって、何かを実行できるかどうかはかなり不自由に思えます。これは、機能/セマンティクスの決定ではなく、スタイル/構文の決定でした。私は何かが足りないのですか?

4

3 に答える 3

9

は必要ありませんtemplate<>。書くだけ:

void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}

メンバーを独自template<>に明示的にインスタンス化する場合は、メンバーの特殊化に関する構文が必要です。既存のスペシャライゼーションのメンバーを定義する場合は省略されます。

template<typename T> struct X { static int i; };
template<> int X<int>::i = 0;  // member instantiation, uses template<>

template<typename T> struct Y { static int i; };
template<> struct Y<int> { static int i; }  // template specialization
int Y<int>::i = 0;  // no template<>
于 2013-01-14T15:14:38.213 に答える
0

template明示的な関数定義はもう必要ありません。void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}

この場合、g++はわずかに良いエラーメッセージを表示しますerror: template-id 'Problem<>' for 'void Test<int>::Problem()' does not match any template declaration

于 2013-01-14T15:16:06.613 に答える
0

これを試して:

// The definition below gives error C2910.
void Test<int>::Problem() 
{
    printf("In Test::Problem(int instantiation)\n");
}

int main()
{
    Test<int> hey; 

    hey.Problem(); 
    return 0;
};
于 2013-01-14T15:19:14.917 に答える