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

如何在C++中实现将不同函数的参数存入数组并调用?

在C++中实现类似Python的函数列表批量调用功能

当然可以实现,不过因为C++是静态类型语言,无法像Python那样直接将不同签名的函数放入同一个容器,需要借助类型擦除或变体类型来统一类型,以下是两种常见的实现方式:

方法一:提前绑定函数与参数

这种方式最直接,把每个函数和对应的参数打包成无参的可调用对象(比如lambda),存入std::vector<std::function<void()>>后直接遍历调用:

#include <iostream>
#include <vector>
#include <functional>
#include <string>

void f1(int a, int b) {
    std::cout << "sum " << a + b << std::endl;
}

void f2(const std::string& str1, const std::string& str2) {
    std::cout << "min len str " << std::min(str1.size(), str2.size()) << std::endl;
}

void f3(int a, int b, int c, int d) {
    std::cout << "product " << a * b * c * d << std::endl;
}

int main() {
    std::vector<std::function<void()>> callables = {
        [](){ f1(1, 2); },
        [](){ f2("test str", "testdtr"); },
        [](){ f3(1, 2, 4, 3); }
    };

    for (const auto& func : callables) {
        func();
    }

    return 0;
}

运行后输出:

sum 3
min len str 7
product 24

方法二:分开存储函数与参数

如果需要像Python那样分别维护函数列表和参数列表,可以用std::variant存储不同签名的函数和不同类型的参数元组,再通过std::visit和std::apply匹配类型并展开参数调用:

#include <iostream>
#include <vector>
#include <variant>
#include <tuple>
#include <string>
#include <algorithm>

void f1(int a, int b) {
    std::cout << "sum " << a + b << std::endl;
}

void f2(const std::string& str1, const std::string& str2) {
    std::cout << "min len str " << std::min(str1.size(), str2.size()) << std::endl;
}

void f3(int a, int b, int c, int d) {
    std::cout << "product " << a * b * c * d << std::endl;
}

int main() {
    // 用variant存储不同签名的函数指针
    using FuncType = std::variant<
        void(*)(int, int),
        void(*)(const std::string&, const std::string&),
        void(*)(int, int, int, int)
    >;
    std::vector<FuncType> functions = {f1, f2, f3};

    // 用variant存储不同类型的参数元组
    using ParamType = std::variant<
        std::tuple<int, int>,
        std::tuple<std::string, std::string>,
        std::tuple<int, int, int, int>
    >;
    std::vector<ParamType> params = {
        std::make_tuple(1, 2),
        std::make_tuple(std::string("test str"), std::string("testdtr")),
        std::make_tuple(1, 2, 4, 3)
    };

    // 遍历匹配函数与参数并调用
    for (size_t i = 0; i < functions.size(); ++i) {
        std::visit([](auto&& func, auto&& args) {
            std::apply(func, args);
        }, functions[i], params[i]);
    }

    return 0;
}

这种方式更贴近Python的写法,但需要提前枚举所有可能的函数签名和参数类型,适合需要动态维护函数与参数列表的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:32:51