C++11中引入了新的类型别名定义方式
using identifier = type-id
曾经在C++中定义类型的别名是采用
typedef identifier type-id;
如果对于通常状况下的类型进行别名声明,两种方式没有区别,可能C++11新引入的方式比较容易理解 。传统的typedef可能会将原类型和新类型的位置弄混,采用=类似于赋值操作更好理解。
别名模板 类型别名可以用于隐藏模板参数
// 这里PRT<const char>为const char*
template <class T>
using PTR = T*;
PTR<const char> str = "Hello World!";
// 少写几个int参数
template<class T>
struct Alloc { };
template<class T>
using Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>
Vec<int> v; // Vec<int> is the same as vector<int, Alloc<int>>
别名模板不能用自身的类型
template<class T>
struct A;
template<class T>
using B = typename A<T>::U; // type-id is A<T>::U
template<class T>
struct A { typedef B<T> U; };
B<short> b; // error: B<short> uses its own type via A<short>::U