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

C++模板类使用std::function时创建对象报错问题求解

错误原因与代码问题分析

代码的核心问题出在std::bind语法使用错误、构造函数传参不匹配两个方面,同时缺少必要的依赖声明,具体如下:

具体问题列表

  • 构造函数传参数量不匹配:你定义的CFuntion类构造函数要求传入3个可调用对象分别初始化三个回调,但是你在make_unique中只传入了1个std::bind生成的对象,参数个数完全不符合要求,直接触发编译报错。
  • std::bind绑定非静态成员函数的用法错误:非静态成员函数调用依赖类实例,绑定的标准格式为std::bind(成员函数指针, 对应类的实例指针/实例, 占位符/实参),每个成员函数都需要单独做绑定。你将三个不同类的成员函数指针全部塞入同一个std::bind的参数列表,既没有提供对应类的实例,也不符合绑定语法,生成的对象根本无法转换为std::function<void()>类型。
  • 缺少必要头文件与命名空间声明:代码中使用的std::function、std::bind需要引入头文件<functional>,std::unique_ptr、std::make_unique需要引入头文件<memory>,cout、endl需要引入头文件<iostream>,且上述标准库组件都属于std命名空间,需要补充using namespace std;或者为所有组件加上std::前缀才能正常编译。
  • 模板类CFuntion的泛型参数T全程未被使用,属于冗余设计,不会直接触发报错但属于不合理代码。
修复后的可运行示例代码
#include <iostream>
#include <functional>
#include <memory>
using namespace std;

template <typename T>
class CFuntion {
public:
    std::function<void()> callback_1;
    std::function<void()> callback_2;
    std::function<void()> callback_3;

    template <typename A, typename B, typename C>
    CFuntion(A cb1, B cb2, C cb3)
        : callback_1(cb1), callback_2(cb2), callback_3(cb3)
    { }
};

class Impl1 {
public:
    void do_something1() {
        cout << "Inside Impl1 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl1 do_something2" << endl;
    }
};

class Impl2 {
public:
    void do_something1() {
        cout << "Inside Impl2 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl2 do_something2" << endl;
    }
};

class Impl3 {
public:
    void do_something1() {
        cout << "Inside Impl3 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl3 do_something2" << endl;
    }
};

int main()
{
    // 先创建三个类的实例,成员函数绑定需要对应实例
    Impl1 i1;
    Impl2 i2;
    Impl3 i3;
    // 分别绑定三个成员函数,作为三个参数传入构造函数
    unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>>(
        std::bind(&Impl1::do_something1, &i1), 
        std::bind(&Impl2::do_something1, &i2),
        std::bind(&Impl3::do_something2, &i3)
    );
    ptr1->callback_1();
    ptr1->callback_2();
    ptr1->callback_3();

    system("pause");
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:54:03