C++模板

来源:互联网 发布:centos 7安装ngrok 编辑:程序博客网 时间:2024/06/06 03:29

下面是 compare 的模板版本:

     // implement strcmp-like generic compare function     // returns 0 if the values are equal, 1 if v1 is larger, -1 if v1 is smaller     template <typename T>     int compare(const T &v1, const T &v2)     {         if (v1 < v2) return -1;         if (v2 < v1) return 1;         return 0;     }

模板定义以关键字 template开始,后接模板形参表,模板形参表是用尖括号括住的一个或多个模板形参的列表,形参之间以逗号分隔。

类模板:

这里先定义它的接口:

     template <class Type> class Queue {     public:         Queue ();                // default constructor         Type &front ();          // return element from head of Queue         const Type &front () const;         void push (const Type &); // add element to back of Queue         void pop();              // remove element from head of Queue         bool empty() const;      // true if no elements in the Queue     private:         // ...     };

类模板也是模板,因此必须以关键字 template 开头,后接模板形参表。Queue模板接受一个名为 Type 的模板类型形参。 

原创粉丝点击