c++模板類成員的聲明和定義應該都放在*.h中,有普通類不同。ios
若是定義放在*.cpp中,最終連接時,會報方法undefined錯誤。c++
參考:http://users.cis.fiu.edu/~weiss/Deltoid/vcstl/templatesspa
若是非要定義在*.cpp中,必定要具體化模板類型,以下,但這樣意味着你要定義無數個。code
因此仍是放在*.h中吧,用到的地方,編譯器會幫你定義具體類型的方法。blog
// error template<typename T> A<T>::func() { // ... } // OK template<> A<int>::func() { // ... }
一個例子:ci
// template.h編譯器
#include <iostream> #ifndef __TEMPLATE_H_ #define __TEMPLATE_H_ class ContextAbstr { public: virtual void log() = 0; }; template<typename T> class Sam { public: Sam() {} virtual ~Sam() {} void func() { _context.log(); return; } public: static int snumber; static void sfunc(); private: T _context; }; // template class's method must be define in *.h // so when be called, different T expand to different definetion // otherwise, ld cann't find the method template<typename T> void Sam<T>::sfunc() { std::cout << "hello template static func" << std::endl; } // regular class's method be declared in *.h, and defined in *.cpp // otherwise, result to mutli-definetion error class Context : public ContextAbstr { public: void log(); }; #endif //__TEMPLATE_H_
// template.cppio
#include "template.h" // template class's member also can be defined in *.cpp, but must specilize the T template<> int Sam<int>::snumber = 10; template<> int Sam<float>::snumber = 15; // regular class's method be defined in *.cpp, avoid mutli-definetion void Context::log() { std::cout << "hello world from template class" << std::endl; }
// test_template.cpp編譯
#include "template.h" int main() { Sam<Context>::sfunc(); Sam<Context>* sam = new Sam<Context>(); sam->func(); Sam<int>* sam_int = new Sam<int>(); std::cout << "int's snumber: " << sam_int->snumber << std::endl; Sam<float>* sam_float = new Sam<float>(); std::cout << "float's snumber: " << sam_float->snumber << std::endl; return 0; }