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

C++中如何将无参函数作为参数传递给另一个函数?

如何传递无参函数给另一个函数

方法1:用std::function(需包含<functional>头文件)

无参且无返回值的函数,对应的std::function类型是std::function<void()>。如果你的函数有返回值(比如返回int),只需把类型改成std::function<int()>即可。

示例代码:

#include <iostream>
#include <functional>

// 定义一个无参函数
void printHello() {
    std::cout << "Hello from the passed function!" << std::endl;
}

// 接收无参函数的函数
void executeFunction(std::function<void()> func) {
    func(); // 调用传入的函数
}

int main() {
    executeFunction(printHello); // 直接传递函数名
    return 0;
}

方法2:用函数指针(更轻量,无需<functional>)

如果只需要传递普通的全局/静态无参函数,用函数指针更直接。无参无返回的函数指针类型是void (*)()。

示例代码:

#include <iostream>

void printHello() {
    std::cout << "Hello from the passed function!" << std::endl;
}

// 用函数指针作为参数
void executeFunction(void (*func)()) {
    func();
}

int main() {
    executeFunction(printHello);
    return 0;
}

额外:传递无参lambda表达式

如果是临时的无参逻辑,直接传lambda也可以,std::function会自动适配:

#include <iostream>
#include <functional>

void executeFunction(std::function<void()> func) {
    func();
}

int main() {
    executeFunction([](){
        std::cout << "Hello from a lambda!" << std::endl;
    });
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:15:00