◆如果说面向对象是一种通过间接层来调用函数, 以换取一种抽象,那么泛型编程则是更直接的抽象,它不会因为间接层而损失效率;
◆不同于面向对象的动态期多态,泛型编程是一种静态期多态,通过编译器生成最直接的代码;
◆泛型编程可以将算法与特定类型,结构剥离,尽可能复用代码;
#include <iostream>#include <string.h>using namespace std;template <class T>T maxValue(T a, T b){cout << "maxValue(T a, T b)" << endl;return a > b? a:b;}//特化处理template<>char* maxValue(char *a, char *b){cout << "maxValue(char *a, char *b)" << endl;return (strcmp(a, b) > 0?(a):(b));}template<class T1, class T2>int maxValue(T1 a, T2 b){return static_cast<int>(a > b? a: b);}int main(){cout << maxValue(1, 2) << endl;cout << maxValue(1.0, 2.9) << endl;char* s1 = "hello";char* s2 = "world";cout << maxValue(s1, s2) << endl;cout << maxValue(1, '2') << endl;return 0;}
求和
#include <iostream>using namespace std;template<int n> //带个特殊值进去struct Sum{enum Value{N = Sum<n-1>::N + n};};template <>struct Sum<1>{enum Value{ N = 1 };};int main(){cout << Sum<100>::N << endl;return 0;}
模板编程的难点很大程度上在于对编译器的理解,我们需要知道怎么帮助编译器提供需要生成代码的信息;
