I am in the process of converting some C# code into C++. I had initially though of replacing the delegates with C-style callbacks. However, on further inspection of the code, I have realized that this is not going to work, as the delegates are being used in a multicast manner, with (pseudo C# code) statements like:
DelegateTypeOne one = new DelegateTypeOne(someCallbackFunc1)
one += new DelegateTypeOne(someCallbackFunc2)
I understand that if the code being ported used the delegates in a single cast fashion, then using regular C style function pointers may have worked. On that note, I have one question, is the following C++ code valid?:
typedef std::vector<int> (CallbackTypeOne*) (const std::string& s, const bool b);
std::vector<int> foo (const std::string& s, const bool b);
CallbackTypeOne func_ptr = NULL;
func_ptr = new CallbackTypeOne(foo); // Note: new being used on a typedef not a type
// or should I just assign the func the normal way?
func_ptr = foo; // this is what I am doing at the moment
My original idea on implementing delegates would be to write an ABC called Delegate, which would be a functor. All other delegates would derive from this ABC, and they will have a STL container (most likely, a list), which will contain a list of any assigned functions, to be called in a sequential order.
This seems to be rather a lot of work, and I'm not even convinced its the most suitable approach. Has anyone done this sort of C# to C++ traqnslation before, and what is the recommended way to implement multicast delegates in C++?
I have two possible solution proposals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With