gpt4 book ai didi

c++ - 当左值传递给 T&& 时,会发生什么?

转载 作者:行者123 更新时间:2023-11-30 01:19:00 24 4
gpt4 key购买 nike

这是C++ Primer 第 5 版中的一个练习:

Exercise 16.45: Given the following template, explain what happens if we call g on a literal value such as 42. What if we call g on a variable of type int? P.690

template <typename T>
void g(T&& val)
{
std::vector<T> v;
}

int main()
{
//g(42);

int i;
g(i);
}

当调用 42 时,它编译了。

i上,编译器报了很多错误,下面粘贴了一部分。

forming pointer to reference type 'int&'

我的问题是

  1. 在这种情况下调用文字值 42 时,为 T 推导出什么类型?

  2. i 上,为什么没有编译?如何理解这些错误信息?

最佳答案

来自 http://thbecker.net/articles/rvalue_references/section_08.html

右值引用的其余两条规则中的第一条也影响旧式左值引用。回想一下,在 pre-11 C++ 中,不允许对引用进行引用:像 A& & 这样的东西会导致编译错误。相比之下,C++11 引入了以下引用折叠规则:

A& & becomes A&
A& && becomes A&
A&& & becomes A&
A&& && becomes A&&

其次,函数模板有一个特殊的模板参数推导规则,它通过对模板参数的右值引用来获取参数:

template<typename T>
void foo(T&&);

在这里,以下内容适用:

  • 当对类型 A 的左值调用 foo 时,T 将解析为 A&,因此,根据上面的引用折叠规则,参数类型有效地变为 A&。
  • 当对类型 A 的右值调用 foo 时,T 将解析为 A,因此参数类型变为 A&&。

那么情况 1,当传递 42 时,您使用右值调用 g,因此 T 被解析为 int因此 g 的参数是 int&& std::vector 是合法的。

在情况 2 中,当传递 i 时,您使用左值调用 g,因此 T 被解析为 int&因此 g 的参数是 int&std::vector<int&> 是合法的。

删除带有 vector 的行,在这两种情况下都可以正常工作。

关于c++ - 当左值传递给 T&& 时,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21624016/

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