Chinaunix首页 | 论坛 | 博客
  • 博客访问: 74007
  • 博文数量: 43
  • 博客积分: 605
  • 博客等级: 中士
  • 技术积分: 355
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-26 18:11
文章分类

全部博文(43)

文章存档

2012年(43)

分类: C/C++

2012-08-08 20:52:40

一、模版:
1.1函数模版
我们可以不用为每个类型定义一个新函数,而是只定义一个函数模板(function template)。函数模板是一个独立于类型的函数,可作为一种方式,产生函数的特定类型版本。

点击(此处)折叠或打开

  1. template <typename T>   //和class T一样
  2.      int compare(const T &v1, const T &v2) //比较大小的模版
  3.      {
  4.          if (v1 < v2) return -1;
  5.          if (v2 < v1) return 1;
  6.          return 0;
  7.      }
  8. int main (int argc, char *argv[])
  9. {
  10.          // T is int;
  11.          // compiler instantiates int compare(const int&, const int&)
  12.          cout << compare(1, 0) << endl;
  13.          // T is string;
  14.          // compiler instantiates int compare(const string&, const string&)
  15.          string s1 = "hi", s2 = "world";
  16.          cout << compare(s1, s2) << endl;
  17.       return 0;
  18. }

1.2类模版:

点击(此处)折叠或打开

  1. template <class Type> class Queue {
  2.      public:
  3.          Queue (); // default constructor
  4.          Type &front (); // return element from head of Queue
  5.          const Type &front () const//通过形参类型指定重载 front 操作的返回类型         void push (const Type &); // add element to back of Queue
  6.          void pop(); // remove element from head of Queue
  7.          bool empty() const; // true if no elements in the Queue
  8.      private:
  9.          // ...
  10.      };

阅读(440) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~