定义模板化功能的特定情况下(C++)
因此,在我.h文件中我有定义模板化功能的特定情况下(C++)
template <class T>
void getValue(T *val, int element, int index);
,然后在我的.cc文件我有一个函数:
template <class T>
void RParser::getValue(T *val, int element, int index)
{
我也有它明确实例:
template void RParser::getValue<char>(char *val, int element, std::string subrecName);
template void RParser::getValue<long long>(long long *val, int element, std::string subrecName);
template void RParser::getValue<float>(float *val, int element, std::string subrecName);
...
这个工作,但我想提出一个完全不同的功能的std :: string
我想:
template <class std::string>
void RParser::getValue<std::string>(std::string * val, int element, int index)
{
,但没有奏效。
任何建议,将不胜感激,
感谢, 乔希
模板,则语法为:
template<>
void RParser::getValue<std::string>(std::string* val, int element, int index) {}
但是正如尼尔的答案所说的,你不需要专门化这个函数模板;超负荷将完成这项工作:
void RParser::getValue(std::string* val, int element, int index) {}
不要使用模板的话 - 只是一个普通的功能:如果你想专门的
void RParser::getValue(std::string * val, int element, int index)
{
}
这只是非法的C++专门化类的模板成员函数。我认为在C++ 00x中这已经放松了。 强调文本
编辑:
class foo {
template <typename T> T bar(const T & t){
return t;
}
template <> int bar<int>(const int & t){
return t + 1 ;
}
};
int main(int c, const char * v[]){
foo f;
}
编译
% gcc /tmp/foo.cpp
/tmp/foo.cpp:6: error: explicit specialization in non-namespace scope ‘class foo’
/tmp/foo.cpp:6: error: template-id ‘bar<int>’ in declaration of primary template
我认为这在模板类中只是非法的吗? – 2010-08-04 14:59:04
_部分_专业化是非法的。 @ jon hanson:这将在_class template_中,而不在_class_中。不同的动物。 – MSalters 2010-08-04 15:02:08
成员函数的特化在类或类模板中是非法的。使用gcc错误输出查看上面的编辑。 – bradgonesurfing 2010-08-04 16:02:25
相关下面的两个答案的时候:你可能会读香草萨特的文章,[ “为什么不专业生产函数模板?”( http://www.gotw.ca/publications/mill17.htm) – 2010-08-04 14:04:12
感谢所有有用的回复,我只是使用Mike的语法专门化模板以解决问题。我意识到你可以重载函数,但我认为(也许是错误的)专门模板是更正确的方法。 – Grammin 2010-08-04 16:09:47