2011-04-18 123 views
4

下面的代码工作正常,一个简单的模板类的定义和使用C++模板专业化方法定义

#include <string> 
#include <iostream> 
using namespace std; 

template<class T> class foo{ 
    public: 
    string what(); 
}; 

template<class T> string foo<T>::what(){ 
    return "foo of type T"; 
} 

int main(){ 
    foo<int> f; 
    cout << f.what() << endl; 
} 

如果我然后添加以下(以上为主,但模板类foo的声明之后; )

template<> class foo<char>{ 
public: 
    string what(); 
}; 
template<> string foo<char>::what(){ 
    return "foo of type char"; 
} 

我得到一个错误从克++

Line 19: error: template-id 'what<>' for 'std::string foo::what()' does not match any template declaration

这里是一个键盘显示s错误:http://codepad.org/4HVBn9oJ

我做了什么明显的误会?或者这是不可能的与c + +模板? 将定义所有内联方法(定义模板<> foo)的工作?

再次感谢所有。

回答

8
template<> class foo<char>{ 
public: 
    string what(); 
}; 
/*template<>*/ string foo<char>::what(){ 
    return "foo of type char"; 
} 

你不需要那么template<>foo<char>在专门化之后已经是一个完整的类型。

+0

错误信息中的what <>指出这一点。请务必仔细阅读错误信息。 ;) – Xeo 2011-04-18 12:39:59

+0

@Xeo:或者因缺乏明确性而哭泣:/ – 2011-04-18 13:02:16

+0

接受,因为它包含了原因并且是第一个。我(不正确地)模仿专门化模板的形式。多谢你们。 – cjh 2011-04-18 23:12:36

0

If I then add the following (above main, but before the declaration of template class foo;)

通用类模板后定义专业化

当编译器看到特化时,它首先需要知道这是专业化的类模板。因此逻辑上,专业化应该在之后出现泛型类模板。

+0

对不起,它应该说没有之前,如果你看过的键盘,这将是明确的。无论如何,谢谢你的时间。 – cjh 2011-04-18 23:06:25

2

写这篇为:

#include <string> 
#include <iostream> 
using namespace std; 

template<class T> class foo{ 
    public: 
    string what(); 
}; 

template<class T> string foo<T>::what(){ 
    return "foo of type T"; 
} 

template<> class foo<char>{ 
public: 
    string what(); 
}; 

string foo<char>::what(){ 
    return "foo of type char"; 
} 

int main(){ 
    foo<char> f; 
    cout << f.what() << endl; 
} 

按预期工作。

+0

谢谢你的回答:) – cjh 2011-04-18 23:09:29