[英]error: invalid initialization of non-const reference of type 'std::function<void()>&' from an rvalue of type 'main()::<lambda()>'|
EDIT : Sorry, I asked this question without a thro understanding of references...编辑:对不起,我在没有对参考文献的理解的情况下问了这个问题......
I seem to be getting this error when I run this code...当我运行此代码时,我似乎收到此错误...
error: invalid initialization of non-const reference of type 'std::function&' from an rvalue of type 'main()::'错误:从“main()::”类型的右值对“std::function&”类型的非常量引用进行无效初始化
#include <bits/stdc++.h>
using namespace std ;
void printfunction(bool a, function <void()> &b)
{
if (a == true)
{
b() ;
}
}
int main()
{
int value = 45 ;
printfunction(true, [value](){cout << "The value is : " << value ;}) ;
}
But, the error disappears when I add a const
before function... like this :但是,当我在
const
之前添加一个const
时,错误就会消失……像这样:
void printfunction(bool a,const function <void()> &b)
The thing is I would like to change the function in the function reference if needed... Is there any other way to do this?问题是如果需要,我想更改函数引用中的函数......还有其他方法可以做到这一点吗? Please let me know if it does indeed exist.
请让我知道它是否确实存在。
Bye,再见,
Samuel塞缪尔
In printfunction
call, lambda expression [value]() {...}
argument must be converted to a temporary function<void()>
object first.在
printfunction
调用中,必须首先将 lambda 表达式[value]() {...}
参数转换为临时function<void()>
对象。
A reference to non-const function<void()>&
only binds to l-values, not temporaries (r-values).对非常量
function<void()>&
的引用仅绑定到左值,而不是临时值(右值)。
A reference to const, on the other hand, can be bound to temporaries.另一方面,对 const 的引用可以绑定到临时对象。 Which is what you observe.
这就是你观察到的。
If you want to modify the std::function
, then you'll need to pass a modifiable (lvalue) parameter:如果要修改
std::function
,则需要传递一个可修改的(左值)参数:
int main()
{
int value = 45;
std::function f = [value](){ std::cout << "The value is : " << value ;};
printfunction(true, f);
}
What you were trying to do isn't much different from writing a function that takes a mutable reference to int
(eg void foo(int& x)
) and then complaining that you can't call foo(5)
.您尝试做的事情与编写一个对
int
进行可变引用的函数(例如void foo(int& x)
)然后抱怨您无法调用foo(5)
并没有太大区别。 (The small difference is that the the lambda-expression is converted to a temporary std::function
- but that still can't be bound to a non-const reference). (小的区别是 lambda 表达式被转换为临时
std::function
- 但仍然不能绑定到非常量引用)。
An alternative would be to change printfunction
to take its argument by value rather than by reference, so that it has its own copy which it may modify.另一种方法是更改
printfunction
以按值而不是按引用获取其参数,以便它拥有自己可以修改的副本。 You'll have to consider the needs of the caller to decide whether that's more appropriate.您必须考虑调用者的需求来决定这是否更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.