#include <functional>
#include <string>
int fn( int a, int & b ) { return a+b; }
struct Fn_struct {
std::string name {};
// std::function<int (int,int&)> my_fn {};
std::function<decltype(fn)> my_fn {};
};
int main()
{
Fn_struct my_fn_struct1 {"fn(a,b)", std::function<decltype (fn)> {fn} };
Fn_struct my_fn_struct2 {"fn(a,b)", {fn} };
Fn_struct my_fn_struct3 {"fn(a,b)", {std::bind( fn, 1, 2) }};
auto fn_b = std::bind( fn, 1, std::placeholders::_1 );
Fn_struct my_fn_struct4 {"fn(a,b)", {std::bind( fn, 1, std::placeholders::_1) }}; // todo: why can't int b be a reference?
}
my_fn_struct4 does not compile, due to failure find a constructor for bind. However if b is not a reference it compiles.
On the other hand fn_b does compile.
Any explanation would be appreciated.
Please don't ask why I want to do this. I would prefer not to use to use pointers to accomplish this unless entirely necessary.
std::bind( fn, 1, std::placeholders::_1 )
returns an object convertible to std::function<int(int &)> my_fn{};
because a function with 2 parameters is passed and the first parameter is bound to 1:
#include <functional>
#include <string>
int fn( int a, int & b ) { return a+b; }
struct Fn_struct {
std::string name {};
std::function<int(int &)> my_fn{};
};
int main()
{
Fn_struct my_fn_struct4 {"fn(a,b)", {std::bind( fn, 1, std::placeholders::_1) }};
}
The line
Fn_struct my_fn_struct3 {"fn(a,b)", {std::bind( fn, 1, 2) }};
works because
If some of the arguments that are supplied in the call to g() are not matched by any placeholders stored in g, the unused arguments are evaluated and discarded.