#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 无法编译,因为找不到绑定(bind)的构造函数。但是,如果 b 不是引用,它会编译。
另一方面 fn_b 确实编译。
任何解释将不胜感激。
请不要问我为什么要这样做。除非完全必要,否则我宁愿不使用指针来完成此任务。
最佳答案
std::bind( fn, 1, std::placeholders::_1 )
返回可转换为 std::function<int(int &)> my_fn{};
的对象因为传递了一个有2个参数的函数,并且第一个参数绑定(bind)为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) }};
}
线
Fn_struct my_fn_struct3 {"fn(a,b)", {std::bind( fn, 1, 2) }};
工作,因为
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.
https://en.cppreference.com/w/cpp/utility/functional/bind
关于C++ 在初始化 std::function 时,我们如何将占位符绑定(bind)到引用/引用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595616/