使用using而非typedef的理由主要有两点:
- typedef不支持模板化,但别名申明可以
- 别名模板可以让人免写”::type“后缀,并且在模板内,对于嵌套typedef的引用经常要求加上typename前缀
对于观点1,对于像相面的引用是允许的:
template<class T>
using MyAllocList = std::list<T, MyAlloc<T>>;
但是typedef就无能为力了,要使用typedef实现上面的引用需要如下定义:
template<class T>
struct MyAllocList {
typedef std::list<T, MyAlloc<T>> type;
};
MyAllocList<Widget>::type lw;
更坏的情况是,如果要在模板内使用typedef来创建一个链表,它容纳的对象型别由模板形参指定的化,那么就要给typedef的名字前一个typename前缀:
template<class T>
class Widget {
public:
typename MyAllocList<T>::type list;
};