You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2019中std::bind的替代方案及互斥锁代码适配问题

针对VS2019中std::bind编译错误的解决方案

问题背景

原代码在VS2017可正常编译:

std::unique_lock<std::mutex>    m_lock(m_mutex_wait_for_message);
m_cond_variable.wait(m_lock, std::bind(&Logging::is_message_available, this));
std::lock_guard<std::mutex>     lock_guard(m_mutex_pushing_message);

切换到VS2019编译时出现以下错误:

  • 'bind': is not a member of 'std'
  • 'bind': function does not take 2 arguments

问题1:互斥锁代码中std::bind的替代方案

最直接且简洁的替代是lambda表达式,它完美适配条件变量wait的谓词要求,语法更直观,VS2019对其支持也更完善:

std::unique_lock<std::mutex>    m_lock(m_mutex_wait_for_message);
// 用lambda替代std::bind,直接捕获this并调用成员函数
m_cond_variable.wait(m_lock, [this](){ return this->is_message_available(); });
std::lock_guard<std::mutex>     lock_guard(m_mutex_pushing_message);

这段代码的逻辑和原std::bind实现完全一致,不会触发编译错误。


问题2:std::bind的通用替代方案

针对所有std::bind的使用场景,有几种通用替代方式:

  • lambda表达式(首选):几乎能覆盖所有std::bind的使用场景,语法清晰,支持捕获外部变量,编译期优化效果更好。示例:
    // 绑定带参数的全局函数
    auto bound_global = [](int a) { return global_func(a + 1); };
    // 绑定成员函数并固定部分参数
    auto bound_member = [this](int val) { return this->process(val, 100); };
    
  • 自定义函数对象:如果需要复用绑定逻辑,可以定义重载operator()的结构体:
    struct IsMessageAvailable {
        Logging* obj;
        IsMessageAvailable(Logging* o) : obj(o) {}
        bool operator()() { return obj->is_message_available(); }
    };
    // 使用方式
    m_cond_variable.wait(m_lock, IsMessageAvailable(this));
    
  • std::mem_fn:专门用于绑定类成员函数,返回可调用对象,适合仅绑定成员函数、无需额外参数的场景(需包含<functional>头文件):
    m_cond_variable.wait(m_lock, std::mem_fn(&Logging::is_message_available), this);
    
  • std::invoke(C++17及以上):更偏向直接调用而非生成绑定后的可调用对象,适合只需单次调用成员函数或普通函数的场景(需包含<functional>头文件):
    bool result = std::invoke(&Logging::is_message_available, this);
    

内容的提问来源于stack exchange,提问作者Thomas Matthews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:10:29