gpt4 book ai didi

c++ - 推导 LValue 引用类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:17 37 4
gpt4 key购买 nike

有很多关于模板参数推导的讨论和澄清,特别是引用折叠和“通用引用”。本题通过相关细节:How does auto deduce type? ,而 Scott Meyers 的这篇论文更详细,可能会提供更多示例和更广泛的上下文:https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers ,以及他的 cppcon 幻灯片:http://www.aristeia.com/TalkNotes/C++TypeDeductionandWhyYouCareCppCon2014.pdf .
我的问题涉及以下代码:

template <typename T> void f(T t) { t = 0; }

int main() {
int i{5};
int &ir{i};
f(ir);
cout << i << endl; // 5
f<decltype(ir)>(ir);
cout << i << endl; // 0
}

为什么我的模板函数 f 不能推断出它们的类型是 int &?根据 Scott Meyers 的幻灯片(幻灯片 7),ir 是左值引用这一事实被简单地忽略。这完美地解释了这种行为,但为了完美地解释那个,我花了一些时间阅读引用资料和标准,试图找到它在哪里说了类似的话:

If A is a reference type, the referred type is used by deduction.

这是旧的离线版本的引用资料(我通常使用的),尽管它在标题Conversion Function Template 下说了,但我没有在标准。我发现的关闭我认为来自重载模板的部分排序规则,但我不相信它会在这里应用,即使它是我正在寻找的。


标准中是否有指定此行为的某处,或者它是否被我忽略的其他行为所暗示?我真的很想告诉别人“因为标准中的这些词就在这里,所以不能推断类型 int &。”

最佳答案

C++中没有引用类型的表达式。 变量 ir 的类型是int&,但是表达式 ir 的类型> 是 int。后一种类型用于类型推导,因为函数参数始终是表达式(braced-init-lists 的特殊情况除外)。

参见 [expr.type]/1

If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

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

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