C++中的typedef和using

typedef和using是什麼

typedef:型別定義,將一個型別宣告為另一個型別。

using:別名宣告,為一個型別定義別名。

解決什麼問題

當使用STL容器時,你可能會一遍遍地寫 std::unqiue_ptr>,是不是覺得寫起來很長,看起來也很長?而且如果哪天要改這個結構是不是要把所有出現的都替換一遍?

那麼有沒有什麼辦法來簡化下?於是,typedef和using就派上用場了。

typedef和using區別

typedef是c++98的特性,using是c++11引入的。然而兩者完成的工作是一樣的。下面透過3種使用場景來列出兩者的書寫對比:

1) 類型別名

typedef std::unique_ptr> UPtrMapSS;

using UPtrMapSS = std::unique_ptr>;

2)函式指標

FP是一個指到函式的指標,該函式形參包括:一個int和一個const std::string,沒有返回值。

typedef void (*FP)(int, const std::string);

using FP = void (*)(int, const std::string);

3)模板

templatestruct MyAllocList { //MyAllocList::type是std::list>的別名 typedef std::list> type;};MyAllocList::type lw; //客戶程式碼

templateusing MyAllocList = std::list>; ////MyAllocList是std::list>的別名MyAllocList::type lw; //客戶程式碼

說明:從上面的程式碼可以看出,別名宣告可以模板化,但是typede不行。using可以直接了當地表達模板化,而typedef不得不用巢狀在模板化的struct裡的typedef才能硬搞出來。

typedef和using如何選擇用哪個

總結一下,typede和using的功能相同,但是typedef不支援模板好而using支援。

所以,優先選用using而非typedef。