C++ 使用using起別名


使用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

來看一下模板別名。


免責聲明!

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



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