《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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值