文章出處
歡迎轉載:http://www.kanwencang.com/bangong/20161206/63447.html
文章列表
C++11中引入的 std::unique_ptr智能指針是個好用的東西,在我們使用 unique_ptr的時候往往會寫出這樣的類型 std::uniqeu_ptr<:string>>,看上去很臃腫,因此大多數的時候我們會選擇使用 typedef進行類型的重定義,簡化類型名稱。可是在C++11中引入了一個 using別名的機制,相比較而言引入這個機制會有其深層次的用意。 <:string>
typedef void(*FP)(int,const std::string&);using FP = void(*)(int,const std::string&);
看上去 using別名機制更加清晰,這或許是引入 using別名機制的原因之一吧。
templateusing aliasList = std::list ;aliasList li;template struct aliasList { typedef std::list type;};aliasList ::type li;
typedef沒有辦法在模板聲明的作用域中做類型重定義,必須放在一個自定義類型作用域內。而using沒有這個限制除了上面提到的兩點外 using還有一些其他的優點,比如對于嵌套類型來說不需要使用 typename。
templateclass Widget { private: typename aliasList ::type list;};
使用 typedef定義的嵌套類型在模板中需要使用 typename,至于為什么可以參考cppreference
對于 using來說則不一樣,因為使用了 using就不會有 ::type這樣的后綴,因為這個后綴會讓編譯器迷惑這到底是類型還是成員變量,使用 using則避免了這個問題,因為沒有 ::type,并且 aliasLitst
std::remove_const::type;std::remove_reference ::type;std::add_lvalue_reference ::type;
到了C++14上面的 ::type都可以去掉了。
就愛閱讀www.92to.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。,std::string>,std::string>歡迎轉載:http://www.kanwencang.com/bangong/20161206/63447.html
文章列表
全站熱搜