使用using与typedef来定义别名

在C++中,using与typedef这两个关键词是大家用的比较多的,using关键词用的最多的是using namespace的搭配如using namespace std;而typedef用来设为某个类型设置一个别名,如typedef unsigned long long uint64;不过,可能有些不知道,其实using也可以用来设置别名,在这种情况下,它与typedef所表述的意思没有区别。使用using来设置一个别名方法如下:

using uint64 = unsigned long long;

C++标准上描述为:

A typedef-name can also be introduced by analias-declaration. The identifier following the using keyword becomes atypedef-name and the optional attribute-specifier-seq following the identifierappertains to that typedef-name. It has the same semantics as if it wereintroduced by the typedef specifier. In particular, it does not define a newtype and it shall not appear in the type-id

 因此在普通的类型名定义时,理论上讲二者是没有区别的,当然,我们知道,还有一种方式定义类型别名,效果也是一样的,那就是#define。

using与typedef在C++11标准以后对于模板类型别名声明有了一点区别。考虑到如下写法:

template <typename T>
typedef std::vector<T> v;//使用typedef


template <typename T>
using v = std::vector<T>;//使用using

看起来好像是都可以的写法,但是使用typedef时,编译器会报错error: template declaration of ‘typedef’

也就是说,C++编译器不支持使用typedef关键词为模板类设置别名,但是使用using的方式声明一个关键词却是允许的,只是这个是C++11标准才有的,如果在编译时不加上--std=c++11使用新的标准的话,编译器一样会报错。



posted @ 2017-05-02 09:29  重复啦  阅读(13805)  评论(0编辑  收藏  举报