Reputation: 95
Hey i want to implement delegate in c++ i know how to do in c# i posting my code but don't know how i convert this to 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");
}
}
now whenever i call printText it will automatically call the OnPrint() of Drived class so is there anyway to implement this to c++?
Upvotes: 0
Views: 261
Reputation: 2395
C# does a lot of management behind the scenes. Broadly, a delegate in C# is a container of function references.
In C++, you can create a similar delegate by using a functor template that wraps an object instance and a member function for class member functions, and also one that just wraps a function (for non members). Then you can use a standard container to maintain the list/array/map/etc of the instances of the functors, and this will provide you with the functionality of the C# delegate and also allow adding and removing 'actions' (C#: += and -=).
Please see my answer here on how you can create such a templated functor for class members. The non-member case is simpler since it does not wrap an object instance.
Upvotes: 1
Reputation: 2797
Take a look at function pointers: http://www.newty.de/fpt/index.html
A function pointer is a pointer that points to a specific function, basically what a delegate is.
Look at this: What is the difference between delegate in c# and function pointer in c++?
Upvotes: 0