demo.h
#pragma once
#include <cstring>
// 函数的特化
template <class T>
T max(T a, T b){
return a > b ? a : b;
}
template<>
char* max(char* a, char *b){
return strcmp(a, b) > 0 ? a : b;
}
// 类内某函数的特化
template<class T>
class Demo{
private:
T pt1, pt2;
public:
Demo(T p1, T p2) :pt1(p1), pt2(p2){}
T max() const {
return pt1 > pt2 ? pt1 : pt2;
}
};
template<>
char* Demo<char*>::max()const{
return strcmp(pt1, pt2) > 0 ? pt1 : pt2;
}
main.cpp
#include <iostream>
#include <string>
#include "demo.h"
using namespace std;
int main(){
cout << max<string>("aaa", "bbb") << endl;
cout << max<char*>("ccc", "ddd") << endl;
Demo<string> demo("aaa","bbb");
cout << demo.max() << endl;
Demo<char*> obj("ccc","ddd");
cout << obj.max() << endl;
return 0;
}
/*
OUTPUT:
bbb
ddd
bbb
ddd
*/