問題描述
始終考慮到包含我的模板化類的以下頭文件至少包含在兩個 .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
}
但請注意特化方法中的內(nèi)聯(lián).由于方法被定義了多次,因此需要避免鏈接器錯誤(在 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
?代碼不應(yīng)在每次使用時重復(fù).我搜索過谷歌,在 SO 中閱讀了一些問題,并嘗試了許多建議的解決方案,但都沒有成功構(gòu)建(至少在 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).
謝謝!
推薦答案
與簡單函數(shù)一樣,您可以使用聲明和實現(xiàn).放入您的標(biāo)題聲明:
As with simple functions you can use declaration and implementation. Put in your header declaration:
template <>
void TClass<int>::doSomething(std::vector<int> * v);
并將實現(xiàn)放入您的一個 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
}
不要忘記刪除內(nèi)聯(lián)(我忘記并認(rèn)為此解決方案不起作用:)).在 VC++2005 上檢查
Don't forget to remove inline (I forgot and thought this solution will not work :) ). Checked on VC++2005
這篇關(guān)于模板化類中單個方法的模板特化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!