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

C++使用std::bind绑定类方法入队时参数未绑定及编译错误问题

问题原因

  • 第一个编译错误:std::queue的pop()方法仅负责移除队首元素,无返回值,你需要先调用front()获取队首元素后再执行pop()。
  • 第二个编译/逻辑错误:你使用std::bind时已经完成了Parser::parse所有参数的绑定:
    类成员方法Parser::parse的调用需要两个参数:第一个是隐式的Parser*类型的this指针,第二个是显式的File_Descriptor*参数。你已经通过bind分别绑定了&file_descr.parser作为this指针、&file_descr作为显式参数,此时绑定生成的可调用对象不需要传入任何参数,你错误声明了function<void(File_Descriptor*)>类型,应该改为function<void()>。

修正后的main.cpp代码

#include <functional>
#include <queue>
#include "file_descriptor.h"
#include "parser.h"
using namespace std;
int main(){
    File_Descriptor file_descr(123);
    // 绑定完所有参数的可调用对象类型为void()
    function<void()> task = bind(&Parser::parse, &file_descr.parser, &file_descr);
    
    queue<function<void()>> task_queue;
    task_queue.push(task);
    // 先取队首元素再执行pop移除
    function<void()> exec_task = task_queue.front();
    task_queue.pop();
    exec_task();
    return 0;
}

修改后运行会正常输出123,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 03:42:02