简体   繁体   English

TR1功能组播

[英]TR1 function multicast

How would you implement multicast for TR1 functors? 您将如何实现TR1函数的多播? I have my callback slots implemented like 我有实现我的回调插槽

void setCallback(std::tr1::function<void (std::string)> cb)
{
    this->callback = cb;
}

but need to pass more than one callback in one of them. 但需要在其中之一中传递多个回调。 I don't want to go into more complex solutions like observer, as this is the only case I need multicast so far. 我不想进入更复杂的解决方案,例如观察者,因为这是到目前为止我唯一需要多播的情况。 I also cannot use Boost.Signals (as suggested here ), because I cannot use Boost. 我也不能使用Boost.Signals(如建议在这里 ),因为我不能使用升压。 I don't need to explicitly handle disabling callback when subscriber no longer exist. 当订户不再存在时,我不需要显式处理禁用回调。

You most likely want: 您最可能想要:

void registerCallback(std::tr1::function<void (std::string)> cb)
{
    this->callbacks.push_back(cb);
}

with callbacks a container (whichever you like) of std::tr1::function objects instead of a single one. callbacks的容器(无论你喜欢) std::tr1::function对象,而不是单一的一个。 When dispatching, iterate over the callbacks. 调度时,遍历回调。

Also, if you want to be able to remove callbacks later, you can do something along these lines: 另外,如果您希望以后能够删除回调,则可以按照以下步骤进行操作:

// I use list because I don't want the iterators to be invalid
// after I add / remove elements
std::list<std::function<void(std::string)>> callbacks;

...
typedef std::list<std::function<void(std::string)>>::iterator callback_id;

callback_id register_callback(std::function<void(std::string)> f)
{
    return callbacks.insert(callbacks.end(), f);
}

void unregister_callback(callback_id id)
{
    callbacks.erase(id);
}

Have a sequence of them rather than a single function (ie a vector<...> ), and when calling back, iterate over the sequence and call. 有一个序列而不是一个函数(即vector<...> ),并且在回调时,遍历该序列并进行调用。

eg 例如

std::vector<std::tr1::function<void (std::string)> > callbacks;
auto it = callbacks.begin(), end = callbacks.end();
for(; it != end; ++it)
  (*it)("somestring");

Put them in a list / vector. 将它们放在列表/向量中。 If you have to remove them individually you have to wrap them some how (because they are not comparable). 如果必须单独删除它们,则必须对其进行一些包装(因为它们不可比)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM