妙空

空妙
随笔 - 0, 文章 - 11, 评论 - 0, 引用 - 0
数据加载中……

The typename and export Keywords

Recently, two keywords were added to C++ that relate specifically to templates: typename and export.
Both play specialized roles in C++ programming. Each is
briefly examined.

The typename keyword has two uses.

First, as mentioned earlier, it can be
substituted for the keyword class in a template declaration. For example, the swapargs() template function could be specified like this:
template <typename X> void swapargs(X &a, X &b)
//这里typename代替了class在模版中的声明
{
    X temp;
    temp 
= a;
    a 
= b;
    b 
= temp;
}
Here, typename specifies the generic type X. There is no difference between using class and using typename in this context.

The second use of typename is to inform the compiler that a name used in a template declaration is a type name rather than an object name. For example,
template<class _Kty,
    
class _Ty,
    
class _Pr = less<_Kty>,
    
class _Alloc = allocator<pair<const _Kty, _Ty> > >
    
class map
        : 
public _Tree<_Tmap_traits<_Kty, _Ty, _Pr, _Alloc, false> >
    {    
// ordered red-black tree of {key, mapped} values, unique keys
public:
    typedef map
<_Kty, _Ty, _Pr, _Alloc> _Myt;
    typedef _Tree
<_Tmap_traits<_Kty, _Ty, _Pr, _Alloc, false> > _Mybase;
    typedef _Kty key_type;
    typedef _Ty mapped_type;
    typedef _Ty referent_type;    
// retained
    typedef _Pr key_compare;
    typedef typename _Mybase::value_compare value_compare;
    typedef typename _Mybase::allocator_type allocator_type;
    typedef typename _Mybase::size_type size_type;
    typedef typename _Mybase::difference_type difference_type;
    typedef typename _Mybase::pointer pointer;

这里,可以看到,typedef typename _Mybase::value_compare value_compare来定义一个变量类型。那么这个value_compare的类型来源于_Mybase::value_compare,而这里typename就是指明,这个_Mybase::value_compare是一个类型,而不是一个成员变量。

The export keyword can precede a template declaration. It allows other files to use a template declared in a different file by specifying only its declaration rather than duplicating its entire definition.

posted on 2008-01-08 14:12 龙人 阅读(84) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理