3

我正在尝试使用 TR1 中的功能创建类似 C# 的多播委托和事件。或 Boost,因为 boost::function (大部分)与 std::tr1::function 相同。作为概念证明,我尝试了这个:

template<typename T1>
class Event
{
private:
 typedef std::tr1::function<void (T1)> action;
 std::list<action> callbacks;

public:

 inline void operator += (action func)
 {
  callbacks.push_back(func);
 }

 inline void operator -= (action func)
 {
  callbacks.remove(func);
 }

 void operator ()(T1 arg1)
 {
  for(std::list<action>::iterator iter = callbacks.begin();
   iter != callbacks.end(); iter++)
  {
   (*iter)(arg1);
  }
 }
};

哪个有效,有点。该行callbacks.remove(func)没有。当我编译它时,我收到以下错误:

error C2451: conditional expression of type 'void' is illegal

list这是由函数中的标题的第 1194 行引起的remove。这是什么原因造成的?

4

3 回答 3

5

如果您正在寻找 C++ 中的多播委托,那么最好的选择是Boost.Signals2。您还可以使用Boost.Bind来实现将成员函数用于回调。

You can look at my example here for simple usage of Boost.Signals and Boost.Bind.

Boost.Signal provides lifetime management facilities to ensure that events are not published to subscribers that no longer exist.

于 2010-02-09T05:14:38.207 回答
4

I think this is exactly same problem: comparing-stdtr1function-objects

(basically you can't compare functors, that's why erase or anything using operator== won't work)

于 2010-02-09T05:15:04.380 回答
0

You should look into Sutter's Generalizing Observer

于 2010-02-13T23:24:07.973 回答