"Effective Modern C++" study notes of the three terms: understanding decltype

decltype is a new keyword in C++11. Its main application scenario is the scenario where the return value depends on the type of the formal parameter. Generally speaking, the results decltype tells you are almost the same as what you predicted, so I won't repeat them here, just remember the following points:

decltype(expression) var; The specific judgment logic is as follows: (1) If the expression is not enclosed in parentheses, the type is exactly the same as the expression, for example, const int i =0; decltype(i) var; then var is const int. (2 ) If expression is a function call, var is the same as the return value of the function. Note that the function will not be called at this time. The compiler obtains the return type through the function prototype (3) If expression is an lvalue and is enclosed in parentheses, var is a reference to its type. For example, int i =0; decltype((i)) var; then var is int&, (4) the above conditions are not satisfied, then var is exactly the same as expression. For example, long i =0; decltype(i+6) var; this When var is a long type.

Shorthand

  • In most cases, the derivation result of decltype is exactly the same as your prediction
  • For an lvalue expression of type T, unless the expression has only one name, decltype will always be deduced as T&
  • C++14 supports decltype (auto), the usage is the same as auto, it will deduce the type from its initialization expression, but its type derivation uses the rules of decltype

 

Guess you like

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