1.包含編譯模型(inclusion compilation model). 函數聲明放在頭文件中,定義放在源文件中。頭文件尾包含源文件。據說會出現一個模板實例化多次從而導致編譯時性能顯著降低。
//template.cpp
template<typename T>
void print(const T &v)
{
cout << "T = " << v <<endl;
}
//template.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
template<typename T>
void print(const T &v);
#include "template.cpp"
#endif
//main.cpp
#include<iostream>
#include "template.h" //#include"template.cpp" 用這條命令代替也可以。
using namespace std;
int main()
{
print(1); //ok
return 0;
}
2. 分別編譯模型(seperate compilation model).函數聲明和類定義放在頭文件中,帶export關鍵字的函數定義和類聲明放在源文件中。源文件尾包含頭文件。(不知道理解的對不對,用的編譯器不支持分別編譯,暫時無從判斷了)
//the template definition goes in a separately-compiled source file
export template<typename T>
T print(const T&v) /*...*/
//class template header goes in shared header file
template <class T> class cl{...};
//cl.cpp implementation file declares cl as exported
export template <class T> class cl;
#include "cl.h"
//cl member definitions


文章來源:http://liyuxia-life.spaces.live.com/Blog/cns!DA1B364675ACF35!265.entry