2013-11-28 73 views
-1

編寫C++模板的時候,我有一個問題,讓我們來檢查代碼:關於C++模板錯誤

abc.h 

class ABC 
{ 
public: 
     template <class T> 
     T getSomething(const std::string& name, ABC* owner = 0); 
     ABC* getSomething(const std::string& name); 
}; 

abc.cpp 


#include "abc.h" 

template <class T> 
T ABC::getSomething(const std::string& name, ABC* owner) 
{ 
     return dynamic_cast<T>(owner ? owner->getSomething(name) : getSomething(name)); 
} 


ABC* ABC::getSomething(const std::string& name) 
{ 
     return NULL; 
} 

,我的主要功能將是這樣的:

int main() 
{ 
     ABC abc; 
     ABC* test = abc.getSomething<ABC*>("hello", NULL); 
} 

當我把我的主要在這個abc.cpp並編譯它,沒有問題一切正常

但問題出現在我使用這個abc.cpp(後來我編譯成abc.o),然後把我的主函數在不同的文件(比如說,def.cpp)。

我真是奇怪的錯誤,該錯誤表示:

/tmp/ccn1H4Bg.o: In function `main': 
def.cpp:(.text+0x4a): undefined reference to `ABC* ABC::getSomething<ABC*>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, ABC*)' 
collect2: ld returned 1 exit status 

大家能幫助我什麼,我錯在這裏做什麼?

謝謝!

回答

2

這是因爲編譯器不支持單獨的模板編譯。將abc.cpp中的模板代碼移至abc.h即可解決此問題。像這樣:

//abc.h 
class ABC 
{ 
public: 
     template <class T> 
     T getSomething(const std::string& name, ABC* owner = 0); 
     ABC* getSomething(const std::string& name); 
}; 

template <class T> 
T ABC::getSomething(const std::string& name, ABC* owner) 
{ 
     return dynamic_cast<T>(owner ? owner->getSomething(name) : getSomething(name)); 
} 

//abc.cpp 
ABC* ABC::getSomething(const std::string& name) 
{ 
     return NULL; 
} 

//def.cpp 
int main() 
{ 
     ABC abc; 
     ABC* test = abc.getSomething<ABC*>("hello", NULL); 
}