C++ 模板套模板

1.模板类中有成员是模板

#include <iostream>
#include <typeinfo>
using namespace std;

template<class T>
class Outer 
{
public:
  template<class R>
  class Inner 
  {
  public:
    void f();
  };
};

template<class T> 
template <class R>
void Outer<T>::Inner<R>::f()
{
  cout << "Outer == " << typeid(T).name() << endl;
  cout << "Inner == " << typeid(R).name() << endl;
  cout << "Full Inner == " << typeid(*this).name() << endl;
}

int main() 
{
  Outer<int>::Inner<bool> inner;
  inner.f();
} /**////:~

//output:
//Outer == int
//Inner == bool
//Full Inner == class Outer<int>::Inner<bool>
//Press any key to continue . . .

  2、模板类参数是模板

// A print function for standard C++ sequences
#include <iostream>
#include <list>
#include <memory>
#include <vector>
#include <deque>
using namespace std;

template<class T, template<class U, class = allocator<U> >
                  class Seq>
void printSeq(Seq<T>& seq) 
{
  for (typename Seq<T>::iterator b = seq.begin();
       b != seq.end();)
    cout << *b++ << endl;
}

int main() 
{
  // Process a vector
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  printSeq(v);
  // Process a list
  list<int> lst;
  lst.push_back(3);
  lst.push_back(4);
  printSeq(lst);

  // Process a deque
  deque<int> d;
  d.push_back(5);
  d.push_back(6);
  printSeq(d);
} /**////:~

  注意:typename 通知编译器被限定的标识符应该为类型,不同与typedef 是定义新的类型。

原文地址

 

原文链接: https://www.cnblogs.com/linlf03/archive/2011/11/21/2257148.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 模板套模板

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/36896

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午1:37
下一篇 2023年2月8日 下午1:37

相关推荐