c++ - 由于抽象模板 arg 的实例化,boost::lambda 表达式无法编译。任何解释和/或解决方法?

标签 c++ boost abstract-class shared-ptr boost-lambda

我正在学习 boost::lambda,并且我已经设法创造了一个我目前所知道的无法解决的情况。

显然在 boost::lambda 的内部,以下示例导致尝试实例化抽象类 AbstractFoo,并阻止 lambda 表达式编译。问题是我不知道它为什么要实例化它,所以我无法尝试解决它。​​

任何 boost::lambda 专家都可以:

  • 请告诉我为什么会这样?
  • 建议解决方法?

例子:

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>


struct AbstractFoo
{
    typedef boost::shared_ptr<AbstractFoo> Ptr;
    virtual int it() const = 0;
};

struct Bar : public AbstractFoo
{
    typedef boost::shared_ptr<Bar> Ptr;
    virtual int it() const { return 3; }
};

typedef AbstractFoo Foo;  // Comment this out
//typedef Bar Foo;        // and this in to make this example compilable

int main()
{
  namespace bll = boost::lambda;

  boost::function< bool (const Foo::Ptr &)> func;
  func = (bll::protect(bll::bind( &Foo::it, *bll::_1))(bll::_1) == 3);

  return 0;
}

编译失败(在 gcc 4.4.3 上,boost 1_40),出现一个怪物模板错误,其重要部分似乎是:

error: cannot declare field 
           ‘boost::tuples::cons<AbstractFoo,boost::tuples::null_type>::head’ 
       to be of abstract type ‘AbstractFoo’
       because the following virtual functions are pure within ‘AbstractFoo’:
            virtual int AbstractFoo::it() const

最佳答案

正如您所发现的,您不能那样做,因为需要复制对象,但在这种情况下它不能被实例化,因为它包含一个纯虚方法。最简单的解决方案是使用指针传递它:

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>

#include <iostream>

struct AbstractFoo
{
    typedef boost::shared_ptr<AbstractFoo> Ptr;
    virtual int it() const = 0;
};

struct Bar : public AbstractFoo
{
    typedef boost::shared_ptr<Bar> Ptr;
    virtual int it() const { return 3; }
};

typedef AbstractFoo Foo;  // Comment this out
//typedef Bar Foo;        // and this in to make this example compilable

int main()
{
  namespace bll = boost::lambda;

  boost::function< bool ( const Foo * )> func;
  func = ( bll::protect( bll::bind( &Foo::it, bll::_1 ) )( bll::_1 ) == 3);
  //func = bll::bind( &Foo::it, bll::_1 );

  Foo::Ptr p( new Bar );
  std::cout << std::boolalpha << func( p.get() ) << std::endl;
}

更准确地说,这是:

*bll::_1

需要实例化和复制AbstractFoo类型的对象

关于c++ - 由于抽象模板 arg 的实例化,boost::lambda 表达式无法编译。任何解释和/或解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6841680/

相关文章:

C++ 重写语法

c++ - 移动后未绘制 SFML 形状

c++ - 为什么在 dlopen 函数中传递的 std::any 的 std::any_cast 会引发错误

c++ - 抽象类(接口(interface))中的运算符重载

c++ - Boost.Spirit.Qi : dynamically create "difference" parser at parse time

c++ - boost::program_options 未定义引用

c# - 从抽象类引用继承的 EntitySet 的 dapper PropInfo Setter 为 null

c++ - IPv6 连接错误 WSAEAFNOSUPPORT

c++ - 具有基本类型的复制构造函数和赋值运算符

c++ - 如何遍历一个boost::multi_array