《Effective Modern C++》第1章学习记录
作者:互联网
Deducing Types
- 变化
C++98只支持函数模板(function template)的类型推导
C++11增加了auto 和decltypes
C++14在C++11的基础上扩展了auto和decltype的适用范围
- 好处
在一处改变原类型,可自动推导出其它地方的类型
- 特点
大部分类型自动推导发生在函数模板调用上
Item1: Understand template type deduction
- Bad news
When the template type deduction rules are applied in the context of auto, they sometimes seem less intuitive than when they’re applied to templates.
-
函数模板类型参数推导三种可能
- 参数是指针或者引用
- 参数是universal reference
- 参数不是指针也不是引用
-
Universal reference type
- T&&
- type deduction distinguishes between lvalue and rvalue
-
ParamType is Neither a Pointer nor a Reference
- That means that param will be a copy–a new object
- That’s why expr’s constness (and volatileness, if any) is gnored
-
Array Arguments
- array-to-pointer rule
void myFunc(int param[])
void myFunc(int* param) // the same as above
f(name);
-
const char (&)[13]
-
T (&)[N]4
-
Function Arguments
- fucntion-to-pointer decay
Item2: Understand auto type deduction
- deducing types for auto is, with only one exception, the same as deducing types for templates
auto x1 = 27;
auto x2(27);
auto x3 = {27};
auto x4{ 27 4};
- The treatment of braced initializers is the only way in which auto type deduction and template type deduction differ
Item3: Understand decltype4
- decltype almost always yields the type of a variable or expression without any modifications
Item4:Know how to view deduced types
Things to remember:
- Deduced types can often be seen using IDE editors, compiler error messages, and the Boost TypeIndex library
- The results of some tools may be neither helpful nor accurate, so an undersatnding of C++'s type deduction rules remains essential.
标签:27,Effective,auto,Modern,C++,deduction,template,type 来源: https://blog.csdn.net/tanshiqian/article/details/112915461