◆如果说面向对象是一种通过间接层来调用函数, 以换取一种抽象,那么泛型编程则是更直接的抽象,它不会因为间接层而损失效率;
    ◆不同于面向对象的动态期多态,泛型编程是一种静态期多态,通过编译器生成最直接的代码;
    ◆泛型编程可以将算法与特定类型,结构剥离,尽可能复用代码;

    1. #include <iostream>
    2. #include <string.h>
    3. using namespace std;
    4. template <class T>
    5. T maxValue(T a, T b){
    6. cout << "maxValue(T a, T b)" << endl;
    7. return a > b? a:b;
    8. }
    9. //特化处理
    10. template<>
    11. char* maxValue(char *a, char *b){
    12. cout << "maxValue(char *a, char *b)" << endl;
    13. return (strcmp(a, b) > 0?(a):(b));
    14. }
    15. template<class T1, class T2>
    16. int maxValue(T1 a, T2 b){
    17. return static_cast<int>(a > b? a: b);
    18. }
    19. int main(){
    20. cout << maxValue(1, 2) << endl;
    21. cout << maxValue(1.0, 2.9) << endl;
    22. char* s1 = "hello";
    23. char* s2 = "world";
    24. cout << maxValue(s1, s2) << endl;
    25. cout << maxValue(1, '2') << endl;
    26. return 0;
    27. }

    求和

    1. #include <iostream>
    2. using namespace std;
    3. template<int n> //带个特殊值进去
    4. struct Sum{
    5. enum Value{N = Sum<n-1>::N + n};
    6. };
    7. template <>
    8. struct Sum<1>{
    9. enum Value{ N = 1 };
    10. };
    11. int main(){
    12. cout << Sum<100>::N << endl;
    13. return 0;
    14. }

    模板编程的难点很大程度上在于对编译器的理解,我们需要知道怎么帮助编译器提供需要生成代码的信息;