欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 【C++】std::bind和std::placeholders

【C++】std::bind和std::placeholders

2025/9/5 21:55:03 来源:https://blog.csdn.net/weixin_45766539/article/details/148543329  浏览:    关键词:【C++】std::bind和std::placeholders

std::bind是C++11引入的函数适配器模板,用于创建新的可调用对象,其核心语法和功能如下

#include <functional>
auto new_callable = std::bind(callable, arg_list);
  • callable‌:可绑定对象(函数、成员函数、函数对象、lambda等)
  • arg_list‌:参数列表,支持混合固定值和占位符std::placeholders::_N

2. 参数绑定规则

  • 固定值绑定‌:直接传递值或对象,调用时无需再指定
    auto bound = std::bind(func, 10, 20);  // 绑定两个固定参数
    bound();  // 等价于 func(10, 20)
    

    占位符绑定‌:通过std::placeholders::_1_2等动态指定参数位置

    auto bound = std::bind(func, _1, _2);  // 调用时需传入两个参数
    bound(30, 40);  // 等价于 func(30, 40)
    

    3. 成员函数绑定

    需显式传递对象指针或引用,并指定占位符

    class MyClass {
    public:void method(int x) { /*...*/ }
    };
    MyClass obj;
    auto bound = std::bind(&MyClass::method, &obj, _1);  // 绑定对象和成员函数
    bound(42);  // 等价于 obj.method(42)
    

    4. 参数重排与适配

    通过占位符调整参数顺序

    void connect(string ip, int port);
    auto reversed = std::bind(connect, _2, _1);  // 参数顺序反转
    reversed(8080, "127.0.0.1");  // 等价于 connect("127.0.0.1", 8080)
    

    5. 引用参数绑定

    使用std::ref避免拷贝

    void update(int& val);
    int x = 0;
    auto bound = std::bind(update, std::ref(x));  // 绑定引用
    bound();  // x会被修改
    

    6. 返回值类型(可选)

    通过模板参数指定返回类型(需C++17起支持)

    auto bound = std::bind<int>(func, _1);  // 显式指定返回int类型
    

注意事项

  • 性能‌:相比直接调用或lambda有额外开销
  • 可读性‌:复杂绑定逻辑可能降低代码可读性,推荐优先使用lambda
  • 类型安全‌:需确保调用时参数匹配绑定签名

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词