STL_1:模板_1_类模板

  • 继承和组合提供了重用对象代码的方法
  • 模板提供了重用源代码的方法

模板语法

类模板

#include <iostream>
using namespace std;

template<class T>
class Array {
  enum { size = 100 };
  T A[size];
public:
  T& operator[](int index) {
    require(index >= 0 && index < size,
      "Index out of range");
    return A[index];
  }
};

int main() {
  Array<int> ia;
  Array<float> fa;
  for(int i = 0; i < 20; i++) {
    ia[i] = i * i;
    fa[i] = float(i) * 1.414;
  }
  for(int j = 0; j < 20; j++)
    cout << j << ": " << ia[j]
         << ", " << fa[j] << endl;
} ///:~
  • 类模板的定义
 Array<int> ia;
  Array<float> fa;
  • 实例化—-生成两个新的生成类

类模板非内联函数

template<class T>
class Array {
  enum { size = 100 };
  T A[size];
public:
  T& operator[](int index);
};

template<class T>
T& Array<T>::operator[] (int index)
{
   require(index >= 0 && index < size,"Index out of range");
    return A[index];
}
  • template<…>=编译器不在当时为期分配存储空间,而是一直等到模板告知

无类型模板参数

template<class T,size N> class Stack
{
   T data[N];
   size_t count;
  public:
    void push(const &T);   
};

Stack<int , 100> myFixedStack;
  • 内含数字被置于栈。而不是动态内存;
  • N的取值不同,会产生唯一的类类型;

默认模板参数

template<class T,size N=100> class Stack
{
   T data[N];
   size_t count;
  public:
    void push(const &T);   
};
template<class T=int,size N=100> class Stack
{
   T data[N];
   size_t count;
  public:
    void push(const &T);   
};

Stack<> myStack; //实例化

模板参数

  • 接受另一个类模板,作为参数
tempalte<class T>
class Array
{......};

template<class T,template<class> class Seq>
class Container
{
    Seq<T> seq;
public:
    void append(const T &t){Seq.push_back(t);}
    T *  begin(){...}
    T * end()   {...}
};

int main()
{
   Container<int ,Array> container;
   container.append(1);
   .....
}

typename

  • typename可以代替 templaet中的class
  • tempalte <typename T> class X {};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值