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

如何使用std::bind将用户函数绑定到std::function类型成员变量

问题解决

你的代码存在3处明显错误,修改后即可正常编译运行:

  • 错误1:SetCustomBehavior成员函数的入参类型缺失std::array的模板参数N,你写的const std::array<int>&实际应为const std::array<int, N>&,直接导致类型不匹配。
  • 错误2:对std::bind的使用完全多余,你传入的custom_f本身和customCallback的类型完全匹配,直接赋值即可,额外的std::bind以及对占位符使用std::ref反而引发类型适配问题。
  • 错误3:自定义头文件引用写法错误,你自己写的base.h和derived.h属于本地头文件,应该用双引号""包裹而非尖括号<>,尖括号仅用于标准库/系统头文件的引用。

修改后的derived.h完整代码

#include "base.h"
#include <cstddef>

template <std::size_t N>
class DerivedClass : public BaseClass<N> {
public:
    DerivedClass() = default;

    DerivedClass(std::function<std::array<int, N>(const std::array<int, N>&, int)> custom_f)
        : customCallback(std::move(custom_f)) {}

    void SetCustomBehavior(std::function<std::array<int, N>(const std::array<int, N>&, int)> custom_f) {
        customCallback = std::move(custom_f);
    }

    std::array<int, N> CustomBehavior(const std::array<int, N>& user_array, int user_number) override {
        if (customCallback)
            this->my_array = customCallback(user_array, user_number);
        return this->my_array;
    }

private:
    std::function<std::array<int, N>(const std::array<int, N>&, int)> customCallback;
};

其余修改点

仅需将main.cpp中的#include <derived.h>改为#include "derived.h"即可正常编译运行,所有断言都会通过。


内容的提问来源于stack exchange,提问作者giacomo-b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:15:04