woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

模版套模版

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 是定义新的类型。

posted on 2008-09-14 18:13 肥仔 阅读(369) 评论(1)  编辑 收藏 引用 所属分类: C++ 模板

评论

# re: 模版套模版[未登录]  回复  更多评论   

我的怎么不能通过

E:\MAIN work\thinking in c++\TICPP-2nd-ed-Vol-two\code\C05\MemberClass.cpp(19) : error C2059: syntax error : ''template<''
E:\MAIN work\thinking in c++\TICPP-2nd-ed-Vol-two\code\C05\MemberClass.cpp(19) : error C2065: 'R' : undeclared identifier
E:\MAIN work\thinking in c++\TICPP-2nd-ed-Vol-two\code\C05\MemberClass.cpp(25) : error C2143: syntax error : missing ';' before '{'
E:\MAIN work\thinking in c++\TICPP-2nd-ed-Vol-two\code\C05\MemberClass.cpp(25) : error C2447: missing function header (old-style formal list?)
2012-01-02 23:13 | 小杰

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理