gpt4 book ai didi

C++通用引用和LRef参数的类型推导

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

假设我们有一些代码

template <typename T>
void Foo(T&& param);

int x = 5;
// deduced Foo<int&>(int&).
// Argument type A = int. T = int&.
Foo(x);

int& rx = x;
// deduced Foo<int&>(int& &&) -> Foo<int&>(int&).
// But... argument type A = int&, an lvalue reference to int.
// Is T = int& or under the hood it is T = int& &?
Foo(rx);

根据 https://en.cppreference.com/w/cpp/language/template_argument_deduction

4) If P is an rvalue reference to a cv-unqualified template parameter (so-called forwarding reference), and the corresponding function call argument is an lvalue, the type lvalue reference to A is used in place of A for deduction

我想知道的是:“引用折叠”规则是否应用于推导类型 T(而不是 P,参数类型)?

那么我们真的有 'Foo(rx)' T = int& &,它折叠成 T = int& 吗?

最佳答案

请注意,实际上,出于所有技术目的,表达式的类型永远不会被视为引用类型。 [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.

一个值得注意的异常(exception)是 decltype()应用于未加括号的名称或类成员访问表达式。尽管语法将名称视为表达式,但语义结果涉及名称的声明类型而不是表达式的类型和值类别。

所以在你的例子中,xint 类型的左值, 和 rxint 类型的左值.在它们的声明和初始化之后,语言对它们没有任何区别,除非你再次使用 decltype(x)。或 decltype(rx) .

这意味着 Foo(rx) 的模板类型推导与 Foo(x) 完全相同: 类型 Aint , 不是 int& ,并且参数是一个左值。根据你引用的规则,T推导为 int& ,并在替换 T=int& 时到函数类型中,引用折叠规则表示 T&&int& .

关于C++通用引用和LRef参数的类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212510/

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