问题描述
始终考虑包含我的模板类的以下头至少包含在两个 .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 somtehing with a vector of a generic T
}
template <>
inline void TClass<int>::doSomething(std::vector<int> * v) {
// Do somtehing with a vector of int's
}
但请注意专业化方法中的内联。它是必需的代码不具有链接器错误(在VS2008是LNK2005),由于该方法被定义多于一次。我理解这一点,因为AFAIK一个完整的模板专业化是一个简单的方法定义。
But note the inline in the specialization method. It is required for the code not to have 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
?代码不应该在每次使用它时重复。我搜索了Google,在这里阅读一些问题,并尝试了许多建议的解决方案,但没有一个成功建立(至少不是在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 was 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
}
不要忘记删除inline(我忘了,认为这个解决方案不会工作:))。
在VC ++ 2005上检查
Don't forget to remove inline (I forgot and thought this solution will not work :) ).Checked on VC++2005
这篇关于从模板类中单个方法的模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!