gpt4 book ai didi

c++ - 为什么将表达式转换为右值对函数的引用是左值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:34 24 4
gpt4 key购买 nike

在这里,cppreference-lvalue ,我发现

Cast expression to rvalue reference to function is lvalue.

出于好奇,我进行了如下实验:

#include <iostream>

using namespace std;


typedef void (&&funr) (int);
typedef void (&funl) (int);

void test(int num){
cout<<num<<endl;//output:20
}

void foo(funr fun){
fun(10);
}

void foo(funl fun){
fun(20);//call this
}

template <typename T> void foo(T&& fun){
cout<<is_same<T,void(&)(int)>::value<<endl;//true, it is lvalue.
cout<<is_same<T,void(int)>::value<<endl;//false, it isn't rvalue.
}
int main()
{

foo(static_cast<void(&&)(int)>(test));
return 0;
}

事实就是如此。

为什么将表达式转换为右值的函数引用是左值?是因为函数类型不需要移动语义还是其他什么?或者我理解错了这个词。

Cast expression to rvalue reference to function is lvalue

最佳答案

它遵循 C++11 3.10/1 中值类别的定义(强调我的):

  • An lvalue (...) designates a function or an object. ...

  • An xvalue (an “eXpiring” value) also refers to an object, ...

  • An rvalue (...) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.

  • A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. ...

请注意,只有左值类别可以是函数,所有其他类别都只是值或对象。

在 5.2.9/1 中也有回应:

The result of the expression static_cast<T>(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue. ...

至于为什么会这样,我当然只能猜测(不是标准化委员会的一员)。但我的猜测是,拥有函数类型的右值是没有意义的——函数永远不会是临时的,它永远不会处于或接近其生命周期的尽头。

关于c++ - 为什么将表达式转换为右值对函数的引用是左值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29116751/

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