C++中可通过std::function与std::bind实现类似C#委托的功能,支持普通函数、成员函数和lambda;使用函数指针适用于简单回调;通过vector存储function对象可实现多播委托;高性能场景可用模板封装零开销委托。

在C++中没有像C#那样的原生委托(delegate)语法,但可以通过多种方式实现类似的功能。委托的核心是“将函数作为参数传递,并支持多播调用”,常见于事件处理、回调机制等场景。以下是几种常用的C++委托实现方法。
使用std::function + std::bind
这是现代C++中最常用且灵活的方式,结合std::function和std::bind可以轻松实现单播委托。
特点: 支持普通函数、成员函数、lambda表达式,类型安全,语法简洁。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include #include using namespace std; using namespace std::placeholders;
void globalFunc(int x) { cout << "全局函数: " << x << endl; }
class MyClass { public: void memberFunc(int x) { cout << "成员函数: " << x << endl; } };
int main() { // 声明委托 function
delegate; // 绑定全局函数 delegate = globalFunc; delegate(10); // 绑定成员函数 MyClass obj; delegate = bind(&MyClass::memberFunc, &obj, _1); delegate(20); // 绑定 lambda delegate = [](int x) { cout zuojiankuohaophpcnzuojiankuohaophpcn "Lambda: " zuojiankuohaophpcnzuojiankuohaophpcn x zuojiankuohaophpcnzuojiankuohaophpcn endl; }; delegate(30); return 0;}
使用函数指针(仅限普通函数)
对于简单的函数回调,可以直接使用函数指针,但不支持类成员函数。
适用场景: C风格回调,性能要求高,功能简单。
示例:
void callback(int x) {
cout << "Callback called with: " << x << endl;
}
using Delegate = void(*)(int);
Delegate del = callback;
del(42);
实现多播委托(Multicast Delegate)
多播委托允许注册多个函数,依次调用。C++标准库没有直接支持,但可以用容器+function实现。
实现思路: 使用vector存储多个function对象,提供add/remove/invoke接口。
class MulticastDelegate {
vector> handlers;
public:
void add(function func) {
handlers.push_back(func);
}
void invoke(int param) {
for (auto& h : handlers)
h(param);
}};
// 使用示例
MulticastDelegate md;
md.add(globalFunc);
md.add([](int x){ cout
基于模板的高性能委托(仿FastDelegate)
若对性能要求极高(如游戏引擎),可使用模板+union实现类型安全且无虚函数开销的委托。这类实现通常封装this指针和函数地址。
优点: 零开销抽象,调用速度快。
简化示例(仅供理解原理):
templateclass FastDelegate { using FuncPtr = void(T::*)(int); T* obj; FuncPtr func; public: FastDelegate(T* o, FuncPtr f) : obj(o), func(f) {}
void operator()(int x) { (obj-youjiankuohaophpcn*func)(x); }};
// 使用 MyClass c; FastDelegate
fd(&c, &MyClass::memberFunc); fd(100);
基本上就这些。选择哪种方式取决于需求:日常开发推荐std::function,追求性能可用模板委托,需要多播则自行封装容器。C++的灵活性让委托实现既强大又可控。











