在模板中,定义模板类型template<class T>和template<typename T>都是一样的。C++书上说,因为template里面的class和类定义class名字有重合,为了防止歧义,引入typename来取代template中的class。但是,typename并不完全等于class的作用。typename还有一个作用。下面以STL中的源码
在STL中的map源代码文件中,看到map的如下定义:
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::const_pointer const_pointer;
typedef typename _Mybase::reference reference;
typedef typename _Mybase::const_reference const_reference;
typedef typename _Mybase::iterator iterator;
typedef typename _Mybase::const_iterator const_iterator;
typedef typename _Mybase::reverse_iterator reverse_iterator;
typedef typename _Mybase::const_reverse_iterator
const_reverse_iterator;
typedef typename _Mybase::value_type value_type;
....
这里,可以看到,typedef typename _Mybase::value_compare value_compare来定义一个变量类型。那么这个value_compare的类型来源于_Mybase::value_compare,而这里typename就是指明,这个_Mybase::value_compare是一个类型,而不是一个成员变量。