繁体   English   中英

推导类型

[英]Deducing the types

我在遍历Scott Meyer的《 Effective Modern C ++》时试图理解类型推导。

考虑下面的代码片段:

template<typename T>
void f(const T& param); // param is now a ref-to-const; paramType is const T&

int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before

f(x); // T is int, param's type is const int&
f(cx); // T is int, param's type is const int&
f(rx); // T is int, param's type is const int&

他说,由于paramType是引用,因此我们可以按照两步过程来推导T的类型:

  1. 忽略expr引用(如果有的话)(即xcxrx
  2. 模式匹配exprparamType的类型

现在,当cxconst int

cx-> const int

paramType->引用const int

因此,根据所提到的逻辑,由于模式匹配(而不仅仅是int ), T不应该是const int吗? 我知道cxconst已经传递给paramType ,但是他说的是对的吗? 根据经验,他提到的这两个步骤是否遵循? 你怎么做呢?

谢谢!

Scott在他的书中使用了这种“符号”:

template<typename T>
void f(ParamType param); // where `ParamType` depends on T

因此,当paramconst int时,让我们为ParamType进行模式匹配。 我们有:

const T & <----> const int // <----> is symbolic notation for pattern matching

因此T推导为int ,因此ParamTypeconst int&

cxconst int ,则T推导为int因此const T& paramconst int& param ,即paramconst int&类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM