template template parameter模板模板参数笔记----C++学习之路

来源:互联网 发布:name.com 域名转出 编辑:程序博客网 时间:2024/06/05 05:10

  1.如标题所说,也就是在模板中嵌入另一个模板举个例子:

template<typename T,                 template <typename T>                class Container              >class XCls{private:    Container<T> c;public:    ....};
那么怎么取使用呢?

template<typename T>using Lst = list<T,allocator<T>>;
XCls<string,list> mylst1;   XXCls<string,Lst> mylst2;
这里得第二段第一行,mylst1得意思就是,传进去得参数是个list模板,但是这一句是错误得,

因为在真正用得时候,这个list也就是Container要拿去list<string> c;这样看是可以得,但是容器有第二模板参数。

在语法上面是过不去得。

要解决这种问题得话,就使用:

template<typename T>using Lst = list<T,allocator<T>>;
  2.如上所说,因为容器可能会有第二第三模板参数,那么假如我们传入得是一个智能指针?

template<typename T,               template<typename T>                class SmartPtr             >class XCls{private:    SmartPtr<T> sp;public:    XCls() :sp(new T) { }};
那么使用:

XCls<string,shared_ptr> p1;XCls<double,unique_ptr> p2; XXCls<int,weak_ptr> p3; XXCls<long,auto_ptr> p4;
其中有两个错误得不是因为上一个得问题,是因为这两个智能指针本身得问题。
  3.看起来像但是又是模板模板参数:

template<class T,class Sequence = deque<T>>class stack{    friend bool operator==<>(const stack&,const stack&);    frend bool operator< <>(const stack&,const stack&);protected:    Sequence c;    ....};
当这么写得时候:

stack<int> s1;
这个第二参数是一个默认值。

stack<int,list<int>> s2;
如果要写出,也要这样写,但是比较起来会发现,这个list得模板参数已经写死了,必须绑定出来。

所以这不是一个模板模板参数。








阅读全文
0 0
原创粉丝点击