模板化类中单个方法的模板特化

Template specialization of a single method from a templated class(模板化类中单个方法的模板特化)
本文介绍了模板化类中单个方法的模板特化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

始终考虑到包含我的模板化类的以下头文件至少包含在两个 .CPP 文件中,此代码编译正确:

Always considering that the following header, containing my templated class, is included in at least two .CPP files, this code compiles correctly:

template <class T>
class TClass 
{
public:
  void doSomething(std::vector<T> * v);
};

template <class T>
void TClass<T>::doSomething(std::vector<T> * v) {
  // Do something with a vector of a generic T
}

template <>
inline void TClass<int>::doSomething(std::vector<int> * v) {
  // Do something with a vector of int's
}

但请注意特化方法中的内联.由于方法被定义了多次,因此需要避免链接器错误(在 VS2008 中为 LNK2005).我理解这一点是因为 AFAIK 完整的模板特化与简单的方法定义相同.

But note the inline in the specialization method. It is required to avoid a linker error (in VS2008 is LNK2005) due to the method being defined more then once. I understand this because AFAIK a full template specialization is the same as a simple method definition.

那么,我如何删除那个 inline?代码不应在每次使用时重复.我搜索过谷歌,在 SO 中阅读了一些问题,并尝试了许多建议的解决方案,但都没有成功构建(至少在 VS 2008 中没有).

So, how do I remove that inline? The code should not be duplicated in every use of it. I've searched Google, read some questions here in SO and tried many of the suggested solutions but none successfully built (at least not in VS 2008).

谢谢!

推荐答案

与简单函数一样,您可以使用声明和实现.放入您的标题声明:

As with simple functions you can use declaration and implementation. Put in your header declaration:

template <>
void TClass<int>::doSomething(std::vector<int> * v);

并将实现放入您的一个 cpp 文件中:

and put implementation into one of your cpp-files:

template <>
void TClass<int>::doSomething(std::vector<int> * v) {
 // Do somtehing with a vector of int's
}

不要忘记删除内联(我忘记并认为此解决方案不起作用:)).在 VC++2005 上检查

Don't forget to remove inline (I forgot and thought this solution will not work :) ). Checked on VC++2005

这篇关于模板化类中单个方法的模板特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)