C++将同一个类中两个不同名称参数类型相同的函数抽象成一个类型

std::fun 抽象

复制代码
#include <iostream>
#include <functional>

class MyClass {
public:
    void func1(int x) {
        std::cout << "func1: " << x << std::endl;
    }

    void func2(int x) {
        std::cout << "func2: " << x << std::endl;
    }
};

void callFunction(MyClass& obj, std::function<void(int)> func, int x) {
    func(x);
}

int main() {
    MyClass obj;
    callFunction(obj, std::bind(&MyClass::func1, &obj, std::placeholders::_1), 10);  // 调用 func1
    callFunction(obj, std::bind(&MyClass::func2, &obj, std::placeholders::_1), 20);  // 调用 func2
    return 0;
}
复制代码

模版:

复制代码
#include <iostream>

class MyClass {
public:
    void func1(int x) {
        std::cout << "func1: " << x << std::endl;
    }

    void func2(int x) {
        std::cout << "func2: " << x << std::endl;
    }
};

template <typename Func>
void callFunction(MyClass& obj, Func func, int x) {
    (obj.*func)(x);
}

int main() {
    MyClass obj;
    callFunction(obj, &MyClass::func1, 10);  // 调用 func1
    callFunction(obj, &MyClass::func2, 20);  // 调用 func2
    return 0;
}
复制代码

using 函数指针

复制代码
using FuncPtr = void (MyClass::*)(int);

void callFunction(MyClass& obj, FuncPtr func, int x) {
    (obj.*func)(x);
}

int main() {
    MyClass obj;
    callFunction(obj, &MyClass::func1, 10);  // 调用 func1
    callFunction(obj, &MyClass::func2, 20);  // 调用 func2
    return 0;
}
复制代码

 

posted on   邗影  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示