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()::'
#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 :
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 temporaryfunction<void()>
object first.A reference to non-const
function<void()>&
only binds to l-values, not temporaries (r-values).A reference to const, on the other hand, can be bound to temporaries. Which is what you observe.