模板专业化实施

时间:2012-01-23 12:53:18

标签: c++ templates

我必须实现模板特化,在实现构造函数时为专门的模板类编译器生成一些错误。以下是我的代码:

#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)

有关如何解决这些错误的任何线索?

3 个答案:

答案 0 :(得分:1)

mycontainer<void>不是模板,也不是它的构造函数,因此构造函数定义应该只是:

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

答案 1 :(得分:0)

你的原型

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

与专业化中的不匹配。将模板参数留空。

话虽如此:您的C ++看起来并不像您已准备好使用模板。你应该先掌握基础知识。

答案 2 :(得分:0)

您完全专业化的语法错误,您不应使用template<typename T> mycontainer<void>或不使用template<>

为什么呢?请参阅C ++模板书中的引用:

完整的专业化声明以这种方式与普通的类声明相同(它不是模板声明)。唯一的区别是语法和声明必须与之前的模板匹配的事实宣言。 因为它不是模板声明,所以可以使用普通的类外成员定义语法定义完整类模板特化的成员(换句话说,不能指定模板&lt;&gt;前缀):< /强>

也可以这样做

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