template classes or function

来源:互联网 发布:mac 编译android源码 编辑:程序博客网 时间:2024/06/05 01:07

模板类或函数,其实就是用一个 文本去替换类或者函数中的变量,会根据输入的类型而确定为那种类型,也可指定类型。

template <class identifier> function_declaration;
template <typename identifier> function_declaration;

    美其名曰适应各种类型

// class templates


#include <iostream>


template <class T> class pair {
     T value1, value2;
public:
    pair (T first, T second) {


        value1=first;


        value2=second;


    }


    T getmax ();


};


template <class T>


T pair<T>::getmax (){


    T retval;


    retval = value1>value2? value1 : value2;


    return retval;


}


int main () {


    pair<int> myobject (100, 75);


    std::cout << myobject.getmax();


    return 0;


}

0 0