Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multicast delegates in C++

Tags:

c++

c#

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++?

like image 262
Homunculus Reticulli Avatar asked Jan 15 '23 12:01

Homunculus Reticulli


1 Answers

I have two possible solution proposals

  1. Use a vector of function pointers, instead of a function pointer. Define a class that holds a vector of callbacks and has operator() that when invoked will invoke the callbacks
  2. Use boost signals
like image 118
Alex Shtof Avatar answered Jan 23 '23 04:01

Alex Shtof