使用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使用新的標准的話,編譯器一樣會報錯。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM