1. 程式人生 > >C++函式模板宣告和定義分離的方法

C++函式模板宣告和定義分離的方法

    廢話不說,先上程式碼。

// template_test.h
template <class T>
T MyMax(T a,T b);
template float MyMax(float a,float b);
template int MyMax(int a,int b);
// template_test.cpp
#include "template_test.h"
#include <iostream>
using namespace std;

template <class T>
T MyMax(T a,T b)
{
	cout<<typeid(a).name()<<endl;
	return (a>b)?a:b;
}
#include "template_test.h"
#include <iostream>
using namespace std;

int main()
{
	int a=1,b=2;
	cout<<MyMax<int>(a,b)<<endl;
	getchar();
	return 0;
}
     原因應該是編譯器在編譯cpp中函式定義的時候要生成obj檔案,如果不加標頭檔案加重的兩行,編譯器無法確定具體型別,所以最後呼叫的時候出現unresolved externals 錯誤。

     另外,這種方法只適用於函式模板,類模板中成函式還是要宣告和實現在同一檔案中。