C++ 在初始化 std::function 时,我们如何将占位符绑定(bind)到引用/引用参数?

标签 c++ std-function stdbind

#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/

相关文章:

c++ - 具有现有起始值的 C/C++ for 循环

c++ - 不完整类型的无效使用 "class"

c++ - 关于先序树遍历

c++ - 一个 const std::function 包装一个非常量 operator()/mutable lambda

c++ - 如何使用 `std::function` 作为函数参数创建可变参数模板函数?

c++ - 我们是否应该在应用 std::bind 之前检查函数是否为空?

c++ - 在 C++ 中使用 std::bind 和 std::function 时出错

c++ - Base64 encode一个XXTEA加密字符串错误

c++ - 如何使用 std::bind 做到这一点?

c++ - std::bind 如何多次调用复制构造函数