Issue
Here I have the code
void foo(std::function<int(int)> stuff){
//whatever
}
and it is called with
auto fct = [](int x){return 0;};
foo(fct);
Which works great. However, when I change foo
to
void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference
//whatever
}
The code doesn't compile. Why is this the case? I know we can just pass the object to a reference parameter directly, we don't need the &
operator like for pointers. Why can't you pass std::function types by reference?
Solution
You are trying to bind a non-constant reference with a temporary object.
You could use a constant reference.
Here is a demonstration program.
#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);
}
The program output is
100
Without the qualifier const you could write for example
#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);
}
As for the lambda-expression then according to the C++ 17 Standard (8.1.5.1 Closure types)
1 The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.
Answered By - Vlad from Moscow Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.