简体   繁体   English

推导类型

[英]Deducing the types

I am trying to understand type deduction while walking through Scott Meyer's Effective Modern C++. 我在遍历Scott Meyer的《 Effective Modern C ++》时试图理解类型推导。

Consider the code snippet below: 考虑下面的代码片段:

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&

He says that since the paramType is a reference, we can follow a two step procedure to deduce the type of T : 他说,由于paramType是引用,因此我们可以按照两步过程来推导T的类型:

  1. Ignore references (if any) in expr (ie, x , cx and rx ) 忽略expr引用(如果有的话)(即xcxrx
  2. Pattern match the type of expr and paramType 模式匹配exprparamType的类型

Now when cx is a const int : 现在,当cxconst int

cx -> const int cx-> const int

paramType -> reference to const int paramType->引用const int

So, according to the logic mentioned, shouldn't T be a const int due to pattern matching (and not just int )? 因此,根据所提到的逻辑,由于模式匹配(而不仅仅是int ), T不应该是const int吗? I understand that the const ness of cx has been passed over to paramType , but is what he says, wrong? 我知道cxconst已经传递给paramType ,但是他说的是对的吗? Is this 2 step procedure that he has mentioned not to be followed as a rule of thumb? 根据经验,他提到的这两个步骤是否遵循? How do you do it? 你怎么做呢?

Thanks! 谢谢!

In his book Scott uses this "notation": Scott在他的书中使用了这种“符号”:

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

So let's do pattern matching for ParamType when param is const int . 因此,当paramconst int时,让我们为ParamType进行模式匹配。 We have: 我们有:

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

So T is deduced as int , hence ParamType is const int& . 因此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