我正在学习 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/