【问题标题】:Deducing the types推断类型
【发布时间】:2017-03-27 22:21:54
【问题描述】:

我在浏览 Scott Meyer 的 Effective Modern C++ 时试图理解类型推导。

考虑下面的代码 sn-p:

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 -> 常量 int

paramType -> 对 const int 的引用

那么,根据上面提到的逻辑,由于模式匹配,T 不应该是const int(而不仅仅是int)吗?我知道cxconstness 已经传递给paramType,但他说的有错吗?他提到的这个两步程序是否作为经验法则不能遵循?你是怎么做到的?

谢谢!

【问题讨论】:

  • 你歪曲了一些东西。 paramType 是什么?
  • @KerrekSB,它是const T&amp;。我已将其包含在 cmets 中(在代码的第二行)。
  • 不要使用 cmets。仅参考实际代码中的内容。我不知道评论是什么意思。改为“param 的类型”。
  • 如果您将const T&amp; 解释为“const 引用T”而不是“引用const T”,则更容易理解。 const 实体只能绑定到 const 引用,但非 cv 实体可以绑定到 const 和非const 引用。
  • 在大多数情况下,它们实际上是相同的(constint 的引用实际上将int 视为const,无论是否相同),但并非总是如此(对于例如,when working with references to pointersconst int*&amp; 是对 const int* 的非 cv 引用,但 int* const&amp; 是对 const 的引用 int*,这与指向 const int 的指针之间的语法差异相同( const int*) 和一个指向 int (int* const) 的 const 指针。

标签: c++ c++11 effective-c++


【解决方案1】:

his book 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&amp;

【讨论】:

  • 谢谢!这就是我一直在寻找的。不过有一个问题 - 你在 cmets 中提到,where ParamType depends on T - 不是反过来吗?
  • @user6490375 不,ParamTypeT 的类型函数,类似于const T*
  • 我把模式匹配误认为是一个集合交集。 (也许是因为我理解所有匹配的东西都是模式的一部分)。所以我推断 T 是const int
【解决方案2】:

cxconst int 时,T 被推导出为int,因此const T&amp; paramconst int&amp; param,即param 的类型为const int&amp;

【讨论】:

  • 感谢您的回答。然而,鉴于书中提到的两个步骤,我正在寻找答案。我相信理解这两个步骤将有助于推断复杂类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2018-07-03
  • 2017-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多