C++ template模板函式的定義與呼叫
阿新 • • 發佈:2019-01-03
引用《C++primer(第四版)》裡的觀點:
1)標準C++為編譯模板程式碼定義了兩種模型:“包含”模型和“分別編譯”模型。
2)所有編譯器都支援“包含”模型,某些編譯器支援“分別編譯”模型。
方法一:
宣告和實現都放在標頭檔案裡。
在類模板標頭檔案template_compile.h中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
在使用模板的測試檔案use_template.cpp中:
#include<iostream>
#include "template_compile.h"
using namespace std;
void main()
{
base<int> bobj;
cout<<bobj.add_base(2,3)<<endl;
}
方法二:
按C++primer中的“包含”模型,在定義模板類的標頭檔案中的末行用語句:#include “template_compile.cpp”
在類模板標頭檔案template_compile.h中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
#include "template_compile.cpp"
在類模板的實現檔案template_compile.cpp中:
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
測試檔案不變。
方法三
使用define
在類模板標頭檔案template_compile.h中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
#define TEMP
#include "template_compile.cpp"
在類模板的實現檔案template_compile.cpp中:
#ifdef TEMP
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
#endif
測試檔案不變。
方法四
在類模板標頭檔案template_compile.h中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
在類模板的實現檔案template_compile.cpp中:
#include "template_compile.h"
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
在使用模板的測試檔案use_template.cpp中:使用#include “template_compile.cpp”
#include<iostream>
#include "template_compile.cpp"
using namespace std;
void main()
{
base<int> bobj;
cout<<bobj.add_base(2,3)<<endl;
}