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

如何初始化并调用由含std::function的结构体组成的std::array

如何初始化并调用由含std::function的结构体组成的std::array

嘿,我来帮你搞定这个问题!你现在要处理的是类里的std::array,元素是包含std::function的结构体,还要绑定类的成员函数对吧?这里有几个关键点要注意,咱们一步步来。

首先得纠正个小拼写错误:你代码里的hanlder1应该是handler1,这个先改过来哈。

核心问题:成员函数不能直接赋值给std::function

类的非静态成员函数(比如foo1、foo2)和普通函数不一样,它们隐式需要一个this指针来指向当前对象实例,所以不能直接把foo1赋值给std::function<bool()>——因为后者期望的是无参数的可调用对象,而成员函数其实是需要一个A*类型的参数(也就是this)的。解决这个问题有两种常用方法:用std::bind绑定this,或者用捕获this的lambda表达式。

方法一:在构造函数里初始化std::array

最直观的方式是在类的构造函数里逐个给Func_Arr的元素赋值:

#include <array>
#include <functional>

class A {
    struct Functions {
        std::function<bool()> handler1;
        std::function<bool()> handler2;
    };

    bool foo1() { /* 这里写你的函数逻辑 */ return true; }
    bool foo2() { /* 这里写你的函数逻辑 */ return true; }
    bool foo3() { /* 这里写你的函数逻辑 */ return true; }
    bool foo4() { /* 这里写你的函数逻辑 */ return true; }

    std::array<Functions, 2> Func_Arr;

public:
    A() {
        // 方式1:用std::bind绑定this和成员函数
        Func_Arr[0].handler1 = std::bind(&A::foo1, this);
        Func_Arr[0].handler2 = std::bind(&A::foo2, this);

        // 方式2:用lambda捕获this,写法更直观
        Func_Arr[1].handler1 = [this]() { return foo3(); };
        Func_Arr[1].handler2 = [this]() { return foo4(); };
    }
};

方法二:直接在成员变量声明处初始化(C++11及以上支持)

如果你喜欢更简洁的写法,可以直接在Func_Arr的声明处用列表初始化,同样需要用lambda捕获this:

#include <array>
#include <functional>

class A {
    struct Functions {
        std::function<bool()> handler1;
        std::function<bool()> handler2;
    };

    bool foo1() { /* 函数实现 */ return true; }
    bool foo2() { /* 函数实现 */ return true; }
    bool foo3() { /* 函数实现 */ return true; }
    bool foo4() { /* 函数实现 */ return true; }

    // 直接初始化std::array,注意外层的双大括号(C++11的array初始化要求)
    std::array<Functions, 2> Func_Arr = {{
        { [this]() { return foo1(); }, [this]() { return foo2(); } },
        { [this]() { return foo3(); }, [this]() { return foo4(); } }
    }};
};

如何调用这些std::function

初始化完成后,调用就很简单了,直接像调用普通函数一样就行。比如在类的某个成员函数里调用:

class A {
    // ... 前面的代码省略 ...

public:
    void runHandlers() {
        // 调用第一个元素的handler1和handler2
        bool result1 = Func_Arr[0].handler1();
        Func_Arr[0].handler2();

        // 调用第二个元素的handler
        Func_Arr[1].handler1();
        Func_Arr[1].handler2();

        // 建议调用前先检查是否为空,避免抛出std::bad_function_call异常
        if (Func_Arr[0].handler1) {
            Func_Arr[0].handler1();
        }
    }
};

额外提醒

  • 如果你用的是C11之前的版本,std::array和std::function可能不支持,建议升级到C11及以上标准。
  • 调用std::function前最好检查是否为空(比如if (func)),如果是空的会抛出std::bad_function_call异常。

备注:内容来源于stack exchange,提问作者sin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 16:58:11