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

在C++中没有像C#那样的原生委托(delegate)语法,但可以通过多种方式实现类似的功能。委托的核心是“将函数作为参数传递,并支持多播调用”,常见于事件处理、回调机制等场景。以下是几种常用的C++委托实现方法。
这是现代C++中最常用且灵活的方式,结合std::function和std::bind可以轻松实现单播委托。
特点: 支持普通函数、成员函数、lambda表达式,类型安全,语法简洁。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <functional>
#include <iostream>
#include <vector>
<p>using namespace std;
using namespace std::placeholders;</p><p>void globalFunc(int x) {
cout << "全局函数: " << x << endl;
}</p><p>class MyClass {
public:
void memberFunc(int x) {
cout << "成员函数: " << x << endl;
}
};</p><p>int main() {
// 声明委托
function<void(int)> delegate;</p><pre class='brush:php;toolbar:false;'>// 绑定全局函数
delegate = globalFunc;
delegate(10);
// 绑定成员函数
MyClass obj;
delegate = bind(&MyClass::memberFunc, &obj, _1);
delegate(20);
// 绑定 lambda
delegate = [](int x) { cout << "Lambda: " << x << endl; };
delegate(30);
return 0;}
对于简单的函数回调,可以直接使用函数指针,但不支持类成员函数。
适用场景: C风格回调,性能要求高,功能简单。
示例:
void callback(int x) {
cout << "Callback called with: " << x << endl;
}
<p>using Delegate = void(*)(int);
Delegate del = callback;
del(42);</p>多播委托允许注册多个函数,依次调用。C++标准库没有直接支持,但可以用容器+function实现。
实现思路: 使用vector存储多个function对象,提供add/remove/invoke接口。
class MulticastDelegate {
vector<function<void(int)>> handlers;
public:
void add(function<void(int)> func) {
handlers.push_back(func);
}
<pre class='brush:php;toolbar:false;'>void invoke(int param) {
for (auto& h : handlers)
h(param);
}};
// 使用示例 MulticastDelegate md; md.add(globalFunc); md.add([](int x){ cout << "Handler 2: " << x << endl; }); md.invoke(50); // 触发所有注册的函数
若对性能要求极高(如游戏引擎),可使用模板+union实现类型安全且无虚函数开销的委托。这类实现通常封装this指针和函数地址。
优点: 零开销抽象,调用速度快。
简化示例(仅供理解原理):
template<typename T>
class FastDelegate {
using FuncPtr = void(T::*)(int);
T* obj;
FuncPtr func;
<p>public:
FastDelegate(T* o, FuncPtr f) : obj(o), func(f) {}</p><pre class='brush:php;toolbar:false;'>void operator()(int x) {
(obj->*func)(x);
}};
// 使用
MyClass c;
FastDelegate
基本上就这些。选择哪种方式取决于需求:日常开发推荐std::function,追求性能可用模板委托,需要多播则自行封装容器。C++的灵活性让委托实现既强大又可控。
以上就是c++++怎么实现委托(delegate)_c++委托实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号