gpt4 book ai didi

c++ - 推导类型

转载 作者:行者123 更新时间:2023-11-30 01:40:33 25 4
gpt4 key购买 nike

我在阅读 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的类型

现在当 cx 是一个 const int 时:

cx -> const int

paramType -> reference to const int

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

谢谢!

最佳答案

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&

关于c++ - 推导类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com