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

模板类中启动线程调用成员函数报错C2661,如何正确传参?

问题分析与解决方案

错误Error C2661 no overloaded function taking 3 arguments的核心原因是线程构造时传递的参数数量/类型与T::check成员函数的签名不匹配,结合你的代码场景,分两种情况给出修正方案:

情况1:T::check是无参数成员函数

如果check不需要外部参数(比如自身有独立的退出逻辑),你多传了is_work_这个冗余参数,直接移除即可:

template <class T>
void worker<T>::start() {
    is_work_ = true;
    thread_ = std::thread(&T::check, obj); // 仅传递成员函数指针和对象指针
}

情况2:T::check需要接收std::atomic<bool>&类型的参数

如果check需要通过is_work_控制运行(比如循环检查直到is_work_为false),不能直接传递is_work_——因为std::thread默认会复制参数,而std::atomic<bool>是不可复制类型,必须用std::ref传递引用:

首先确保T::check的签名符合要求:

class SomeT {
public:
    void check(std::atomic<bool>& is_running) {
        while (is_running) {
            // 执行检查逻辑
        }
    }
};

然后修正start()函数(需包含<functional>头文件):

#include <functional>

template <class T>
void worker<T>::start() {
    is_work_ = true;
    thread_ = std::thread(&T::check, obj, std::ref(is_work_));
}

额外注意事项

析构worker对象时,需先终止线程再销毁资源,避免未定义行为:

~worker() {
    is_work_ = false;
    if (thread_.joinable()) {
        thread_.join();
    }
    if (obj) {
        delete obj;
        obj = nullptr;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:54:26