能否继承自boost :: function?

4
我想知道是否可以从boost :: function继承。
基本上,为了方便使用,我想要一个类型“Delegate”,它基本上是一个boost :: function。这只是为了在我编写的某些代码中更容易使用。
我曾经将boost :: function typedef为Delegate,但根据我的经验,typedef会对gdb造成严重影响。特别是如果它是模板化的,所以我想避免这种情况(您是否曾经尝试过调试已经被typedef的stl容器?噢,天啊)。
我在网上找到了一些代码,其中提供了某种示例:
template<class Signature>
class Delegate : public boost::function<Signature>
{
public: 
    using boost::function<Signature>::operator();
};

现在,我尝试使用它时遇到了一些错误。一个使用例子如下:
Tank * tankptr = new Tank();
Delegate<void ()> tankShoot(boost::bind(boost::mem_fn(&Tank::Shoot),tankptr));

这会导致诸如以下错误:

error: no matching function for call to ‘Delegate<void ()()>::Delegate(boost::_bi::bind_t<boost::_bi::unspecified, boost::_mfi::mf0<void, Tank>, boost::_bi::list1<boost::_bi::value<Tank*> > >)’
Delegate.h:26: note: candidates are: Delegate<void ()()>::Delegate()
Delegate.h:26: note:                 Delegate<void ()()>::Delegate(const Delegate<void()()>&)

如果我得猜测为什么我收到这些错误,我会说是因为我缺少一个拷贝构造函数,该拷贝构造函数可以接受boost::bind构造函数返回的任何基类。

你有什么想法可以帮我克服这个障碍吗?或者能否向我指出继承自boost::function的好例子?

2个回答

6

从一个类派生并不会自动继承基类构造函数到派生类。您需要在那里创建所有所需的构造函数。


我只是想发表一个类似的答案。他需要一个构造函数,该构造函数接受boost::function<>并将其传递给基类。 - lefticus
我早就想到了。有人知道这样做的任何例子吗?我在语法方面遇到了麻烦,从一个好的例子中受益匪浅。 - sbrett
啊,我想我弄明白了。我必须做类似于`template<class Signature> class Delegate : public boost::function<Signature>{public:using boost::function::operator(); Delegate() : boost::function() {} Delegate(const boost::function& x) : boost::function(x) {}}; `(我的格式很糟糕,抱歉)。 - sbrett
@sbrett:你也可以实现一个模板构造函数 template<class Functor> Delegate(Functor f) : boost::function<Signature>(f){} 并依赖于 Boost.Function 构造函数。 - Xeo

0

我花了很长时间才找到他们网站上boost类“function”的接口文件。

最终,我得到了类似于以下的东西:

template<class Signature>
class Delegate : public boost::function<Signature>
{
public:
  ///use the functor operator from the original class
  using boost::function<Signature>::operator();

  ///base constructor for our new type, 
  Delegate() : boost::function<Signature>() {/*empty*/}

  ///copy constructor for our new type
  Delegate(const boost::function<Signature>& x) : boost::function<Signature>(x) {/*empty*/}

  Delegate& operator=(const Delegate & _delegate)
  {
    boost::function<Signature> x = _delegate;
    try
    {
      dynamic_cast<boost::function<Signature> & >(*this) = x;
    }
    catch(bad_cast &bc)
    {
      cout << "Bad Cast Exception. " << bc.what();
      int * ptr = NULL;
      *ptr = 1; //force seg fault instead of assert
    }
    return *this;
  }
};

我不确定我是否正确使用dynamic_cast(在遵守良好编程实践的情况下),或者我是否需要它在赋值运算符中,但它确实可以工作,并且工作得非常好。


想再补充一点,实际上,尽管上述代码在gcc 4.1.1编译器上可以工作。 - sbrett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接