#include <iostream>
using namespace std;
template<typename t>
t maximum(t a, t b){
cout << "template" << endl;
return a>b?a:b;
}
template<>
const char* maximum(
const char* a,
const char* b){
return strlen(a) > strlen(b)? a:b;
}
//template<>
//char* maximum(char* a, char* b){
// return strlen(a) > strlen(b)? a:b;
//}//如果沒有const 的話,依舊會調用最上面的模板,因為編譯器不能準確匹配,所以必須為const才行。
int main(){
cout << maximum("pfdsfasdakis", "kadf") << endl;
}
#include <iostream>
using namespace std;
template<typename T>
class TestClass{
public:
void F(T pT){
cout << " T version " << endl;
cout << pT << endl;
}
};
template<>
class TestClass<
int>{
public:
void F(
int pT){
cout << "int version " << endl;
cout << pT << endl;
}
void F(char pT){
cout << "int version " << endl;
cout << pT << endl;
}如果這里修改成接受char型的參數,并且在main函數中調用obj2.F('a'),同樣的,會調到該函數,所以說,編譯器是在看到“TestClass<int> obj2;“這句的時候就知道該調用哪個了。
void g(){}
};
//特化的類在編譯器中已經跟原來的類名字不同了,所以是兩個東西,但是編譯器要找一個最符合的名字。TestClass_int 可以在里面修改東西
int main(){
TestClass<
char> obj1;
TestClass<
int> obj2;
obj1.F('A');
obj2.F(10);
obj2.g();
return 0;
}
posted on 2012-06-04 19:57
Dino-Tech 閱讀(322)
評論(0) 編輯 收藏 引用