c# - C++中的委托(delegate)

标签 c# c++ delegates

嘿,我想在 C++ 中实现委托(delegate),我知道如何在 C# 中执行,我发布了我的代码,但不知道如何将其转换为 C++

public class Events {
    public delegate void Action();
    public Action OnPrintTheText = delegate{};
}

public class ABC {
    private Event evt;
    public ABC() {
        evt  = new Event();
    }
    public void printText() {
        evt.OnPrintTheText();
    }
    public Event getEventHandler() {
        return evt;
    }
}
public class Drived {
    private ABC abc;

    public Drived() {
        abc = new ABC();
        abc.getEventHandle().OnPrintTheText += OnPrint;
    }
    ~Drived() {
        abc.getEventHandle().OnPrintTheText -= OnPrint;
    }
    public void OnPrint() {
        Debug.Log("ABC");
    }
}

现在,每当我调用 printText 时,它都会自动调用 Drived 类的 OnPrint(),那么是否可以将其实现为 c++?

最佳答案

C# 在幕后做了很多管理工作。从广义上讲,C# 中的委托(delegate)是函数引用的容器。

在 C++ 中,您可以使用仿函数模板创建类似的委托(delegate),仿函数模板包装对象实例和类成员函数的成员函数,也可以只包装函数(对于非成员)。然后您可以使用标准容器来维护仿函数实例的列表/数组/映射/等,这将为您提供 C# 委托(delegate)的功能,还允许添加和删除“操作”(C#:+=和-=)。

请看我的回答here关于如何为类成员创建这样的模板仿函数。非成员情况更简单,因为它不包装对象实例。

关于c# - C++中的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132023/

相关文章:

swift - 如何使用 Swift 在 MVC 中避免臃肿的 ViewController?

c# - 抛出 HttpException 总是发回 HTTP 500 错误?

c++ - 对于 C++ 模板,有没有办法找到 "valid"输入的类型?

ios - 隐藏类型为 UIKeyboardTypeNumberPad objective c 的键盘

c++ - boost lambda 的使用

c++ - 为什么不调用复制构造函数?

.net - vb.net多线程无法正常工作

c# - TimeStamp_Sys100NS 从 Win32_PerfFormattedData_PerfProc_Process wmi 返回 null

c# - 在 Resharper ContextAction 中抑制 IProgressIndicator

c# - Microsoft.ML 和 Xamarin