使用using起别名
相当于传统的typedef起别名。
typedef std::vector<int> intvec;
using intvec = std::vector<int>; //这两个写法是等价的
- 1
- 2
这个还不是很明显的优势,在来看一个列子:
typedef void (*FP) (int, const std::string&);
- 1
若不是特别熟悉函数指针与typedef,第一眼还是很难指出FP其实是一个别名,代表着的是一个函数指针,而指向的这个函数返回类型是void,接受参数是int, const std::string&。
using FP = void (*) (int, const std::string&);
- 1
这样就很明显了,一看FP就是一个别名。using的写法把别名的名字强制分离到了左边,而把别名指向的放在了右边,比较清晰,可读性比较好。比如:
typedef std::string (Foo::* fooMemFnPtr) (const std::string&);
using fooMemFnPtr = std::string (Foo::*) (const std::string&);
- 1
- 2
- 3
来看一下模板别名。