You need to enable JavaScript to run this app. C++如何将不同签名的函数指针存入map并完成回调调用?
优惠活动
大模型
产品
解决方案
定价
更多

C++如何将不同签名的函数指针存入map并完成回调调用?

现有实现的核心问题
  • 固定签名的std::function<void()>容器无法适配不同参数、不同返回值的回调类型,非静态成员函数自带隐藏this参数,和普通全局函数签名完全不同,直接传入会触发类型不匹配的编译错误,强行强转还会造成栈内存错乱
  • 用裸func*指针存储可调用对象没有自动生命周期管理,存在内存泄漏风险
  • 订阅非静态成员函数时没有绑定所属类实例的上下文,就算存进去也缺少this指针,根本无法正常调用
  • 所有成员回调、start()方法没有显式返回值,会触发未定义行为的编译警告
  • 调用回调时的语法和存储的签名不匹配,按void()类型的可调用对象根本无法传入参数(比如5、"test"这类入参),完全编译不通过
正确实现方案

核心思路是用std::any做类型擦除,让map可以存储任意签名的可调用对象,订阅和获取时通过模板方法适配不同的函数签名,完全匹配你预期的调用逻辑。

修正后的 mySubscriber.h

#pragma once
#include <map>
#include <string>
#include <functional>
#include <any>
#include <stdexcept>

class mySubscriber {
    // 用std::any做类型擦除,存储任意签名的可调用对象
    std::map<std::string, std::any> _subscribes;

public:
    mySubscriber() = default;
    ~mySubscriber() = default;

    // 模板化订阅方法,适配任意签名的可调用对象
    template<typename FuncType>
    void subscribe(std::string fName, FuncType&& func) {
        // 把传入的可调用对象转成标准std::function,做类型统一后存入any
        _subscribes[fName] = std::function<std::remove_reference_t<FuncType>>(std::forward<FuncType>(func));
    }

    // 模板化获取方法,由调用者指定需要的函数签名
    template<typename RetType, typename... Args>
    std::function<RetType(Args...)> getSubscribe(std::string fName) {
        auto find = _subscribes.find(fName);
        if (find == _subscribes.end()) {
            throw std::runtime_error("未找到订阅的回调: " + fName);
        }
        // 类型校验:存储的内容转成指定签名的std::function
        try {
            return std::any_cast<std::function<RetType(Args...)>>(find->second);
        } catch (const std::bad_any_cast& e) {
            throw std::runtime_error("回调[" + fName + "]签名不匹配: " + e.what());
        }
    }
};

修正后的 myMainClass.h

#pragma once
#include <iostream>
#include <string>
#include "mySubscriber.h"

struct myMainClass {
    myMainClass() = default;
    ~myMainClass() = default;

    bool callback1(int iData) {
        std::cout << "callback 1 with iData " << iData << std::endl;
        return true;
    }

    bool callback2(std::string sData) {
        std::cout << "callback 2 with sData " << sData << std::endl;
        return true;
    }

    bool callback3(int iData, std::string sData) {
        std::cout << "callback 3 with iData " << iData << ", sData " << sData << std::endl;
        return true;
    }

    bool start() {
        mySubscriber ss;
        // 订阅时绑定当前实例的this指针,形成可直接调用的可调用对象
        ss.subscribe("callback1", [this](int data) { return this->callback1(data); });
        ss.subscribe("callback2", [this](std::string data) { return this->callback2(data); });
        ss.subscribe("callback3", [this](int a, std::string b) { return this->callback3(a, b); });

        // 调用时显式指定回调的返回值和参数列表
        ss.getSubscribe<bool, int>("callback1")(5);
        ss.getSubscribe<bool, std::string>("callback2")("test");
        ss.getSubscribe<bool, int, std::string>("callback3")(10, "test2");

        return true;
    }
};
关键注意点
  • 因为用了类型擦除存储任意签名的回调,取出时必须显式指定目标函数的返回值和参数列表——编译器无法自动推断你要取的回调类型,这个设计也是为了提前做类型校验,避免运行时的莫名其妙的崩溃
  • 调用getSubscribe的时候,必须和存的时候的签名完全一致:少一个参数、多一个参数、返回值不匹配都会触发bad_any_cast异常,代码里已经加了友好的异常提示
  • 用lambda捕获this的时候要注意生命周期:如果mySubscriber对象的存活时间比myMainClass实例长,就会出现悬垂引用,调用时崩溃,这种情况可以改用智能指针捕获对象实例
  • 不需要手动释放内存,std::any和std::function会自动管理可调用对象的析构,不会出现原来裸指针的内存泄漏问题
  • 代码里已经修正了原来头文件后多余分号、不标准头文件包含的问题,符合C++编码规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 21:27:00