C ++中的多播委派 [英] Multicast delegates in C++

查看:116
本文介绍了C ++中的多播委派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些C#代码转换为C ++。我最初虽然用C风格的回调代替了委托。但是,在进一步检查代码,我意识到这不会工作,因为代表以多播方式使用(pseudo 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)

我理解,如果被移植的代码使用单个转换方式的代理,那么使用常规的C风格函数指针可能工作。注意,我有一个问题,是下面的C ++代码是否有效:

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

我对代码实现的想法是写一个ABC称为Delegate,这将是一个函子。所有其他代理将从这个ABC中派生,并且它们将有一个STL容器(最可能的是一个列表),它将包含任何分配的函数的列表,按顺序调用。

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.

这似乎是相当多的工作,我甚至不相信它的最合适的方法。有没有人做过这种类型的C#到C ++ traqnslation之前,以及什么是在C ++中实现多播委托的方式?

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


  1. 使用函数指针的向量,而不是函数指针。定义一个包含回调向量的类,并且具有在调用时调用回调的operator()。

  2. 使用提升信号

  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

这篇关于C ++中的多播委派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆