为什么按值传递函数有效,而不按引用传递函数



这里有代码

void foo(std::function<int(int)> stuff){
//whatever
}

它被称为

auto fct = [](int x){return 0;};
foo(fct);

效果很好。但是,当我将foo更改为时

void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference
//whatever
}

代码未编译。为什么会出现这种情况?我知道我们可以直接将对象传递给引用参数,我们不需要像指针那样的&运算符。为什么不能通过引用传递std::函数类型?

您正试图将一个非常量引用与一个临时对象绑定。

您可以使用常量引用。

这是一个示范节目。

#include <iostream>
#include <functional>
void foo( const std::function<int(int)> &stuff )
{
int x = 10;
std::cout << stuff( x ) << 'n';
}
int main()
{
auto fct = [](int x){return x * 10;};
foo(fct);
}

程序输出为

100

如果没有限定符const,您可以编写例如

#include <iostream>
#include <functional>
void foo( std::function<int(int)> &stuff )
{
int x = 10;
std::cout << stuff( x ) << 'n';
}
int main()
{
auto fct = [](int x){return x * 10;};
std::function<int(int)> f( fct );
foo(f);
}

至于lambda表达式,则根据C++17标准(8.1.5.1闭包类型(

1 lambda表达式的类型(也是闭包对象(是一个唯一的、未命名的非并集类类型,称为闭包类型,其属性如下所述。

最新更新