模板化类中单个方法的模板特化
始终考虑到包含我的模板化类的以下头文件至少包含在两个 .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
相关文章