2012-01-23 8 views
2

私はテンプレートの専門化を実装する必要があります。以下は、私のコードです:テンプレートの特殊化の実装

#include <iostream> 
using namespace std; 

// class template 

template <typename T> 
class mycontainer 
{ 

T element; 
    public: 
    mycontainer (T arg); 
    T increase() {return ++element;} 
}; 

// class template specialization 
template <> 
class mycontainer <void> { 
    int element; 
    public: 
    mycontainer (int arg); 

    char uppercase() 
    { 
    return element; 
    } 
}; 

template<typename T> mycontainer<T>::mycontainer(T arg){ 
    cout << "hello T" << endl; 
} 

template<typename T> mycontainer<void>::mycontainer(int arg){ 
    cout << "hello Empty" << endl; 
} 

int main() { 
    mycontainer<int> myint (7); 
    mycontainer<void> myvoid (6); 
    cout << myint.increase() << endl; 
    return 0; 
} 

コードは、これらのエラーを生成します。

test.cpp:31:22: error: prototype for ‘mycontainer<void>::mycontainer(int)’ does not match any in class ‘mycontainer<void>’ 
test.cpp:16:26: error: candidates are: mycontainer<void>::mycontainer(const mycontainer<void>&) 
test.cpp:19:5: error:     mycontainer<void>::mycontainer(int) 

これらのエラーを解決する方法上の任意の手がかり?

答えて

0

完全な分業のためのあなたの構文が間違っている、あなたがtemplate<typename T> mycontainer<void>かさえtemplate<>

を使用しません。

なぜですか?

完全な特殊化宣言は、このように通常のクラス宣言と同じです(テンプレート宣言ではありません)。唯一の違いは構文と、宣言が前のテンプレート宣言と一致しなければならないという事実です。 テンプレート宣言ではないため、通常のクラスアウトメンバ定義構文を使用してフルクラステンプレートの特殊化のメンバーを定義できます(つまり、<>接頭辞は指定できません)。

だから、どちらか

mycontainer<void>::mycontainer(int arg){ 
    cout << "hello Empty" << endl; 
} 

を行うことができますかの操作を行います。

#include <iostream> 
using namespace std; 

// class template 

template <typename T> 
class mycontainer 
{ 

T element; 
    public: 
    mycontainer<T>::mycontainer(T arg) 
    { 
     cout << "hello T" << endl; 
    } 
    T increase() {return ++element;} 
}; 

// class template specialization 
template <> 
class mycontainer <void> { 
    int element; 
public: 
    mycontainer (int arg) 
    { 
     cout << "hello Empty" << endl; 
    } 

    char uppercase() 
    { 
    return element; 
    } 
}; 


int main() { 
    mycontainer<int> myint (7); 
    mycontainer<void> myvoid (6); 
    cout << myint.increase() << endl; 
    return 0; 
} 
0

あなたのプロトタイプ

template<typename T> mycontainer<void>::mycontainer(int arg){ 
    cout << "hello Empty" << endl; 
} 

は専門に1と一致していません。テンプレートパラメータは空のままにします。

言われています:あなたのC++は、あなたがテンプレートを使用する準備ができていないように見えます。基本的なことをまず理解しておくべきです。

1

mycontainer<void>はテンプレートではなく、そのコンストラクタではありませんので、コンストラクタの定義は、単にする必要があり、どちらも:

mycontainer<void>::mycontainer(int arg){ 
    cout << "hello Empty" << endl; 
} 
関連する問題