Clause 9 of "Effective Modern C++" study notes: using statement is preferred instead of typedef

Both using alias declaration and typedef declaration can complete a type declaration, but using using can complete this operation very simply and directly. The following will declare the same type separately through the code, and you can see the benefits of using.

//声明指针函数
typedef void(*FP)(int ,double);   //typedef晦涩不直白
using FP = void(*)(int ,double); //using简单直白


//typedef声明一个模板,表示一个链表
template<class T>
struct MyAllocList{
  typedef std::list<T,MyAlloc<T>> type;//typedef晦涩不直白
};

MyAllocList::type myList;  //类型使用晦涩不直白


//using 声明一个模板,表示一个链表
template<class T>
using MyAllocList std::list<T,MyAlloc<T>>;//using简单直白
MyAllocList myList;//类型使用简单直白

In particular, if you want to use a typedef to create a linked list in a template at this time, but the type it contains is specified by template parameters, then you have to add a typename prefix in front of the typedef to indicate that typedef is a type. But using using is completely unnecessary.

//typedef声明一个模板,表示一个链表
template<class T>
struct MyAllocList{
  typedef std::list<T,MyAlloc<T>> type;//typedef晦涩不直白
};

template<class T>
class Widget {
private:
    typename MyAllocList<T>::type list;//必须加上typename,否则编译器不知道其是个类型
};


//using 声明一个模板,表示一个链表
template<class T>
using MyAllocList std::list<T,MyAlloc<T>>;//using简单直白

template<class T>
class Widget {
private:
    MyAllocList<T> list;//so easy
};

Shorthand

  • The typedef declaration does not support templating, but the using alias declaration supports
  • Using the alias using template can avoid writing the "::type" suffix, and in the template, the reference to the embedded typedef is often required to add the typename prefix

 

Guess you like

Origin blog.csdn.net/Chiang2018/article/details/114190198