使用boost :: bind重载运算符增加未定义的引用错误

时间:2013-05-02 18:46:11

标签: c++ templates boost linker boost-bind

有问题的代码:

boost::function<bool()> isSpecialWeapon = boost::bind(&WeaponBase::GetType,this) == WeaponType::SPECIAL_WEAPON;

我得到的错误是这样的:

 undefined reference to `boost::_bi::bind_t<bool, boost::_bi::equal, 
 boost::_bi::list2<boost::_bi::bind_t<WeaponType::Guns, 
 boost::_mfi::cmf0<WeaponType::Guns, WeaponBase>,  
 boost::_bi::list1<boost::_bi::value<WeaponBase*> > >, 
 boost::_bi::add_value<WeaponType::Guns>::type> > boost::_bi::operator==
 <WeaponType::Guns, boost::_mfi::cmf0<WeaponType::Guns, WeaponBase>, 
 boost::_bi::list1<boost::_bi::value<WeaponBase*> >, WeaponType::Guns>
 (boost::_bi::bind_t<WeaponType::Guns, boost::_mfi::cmf0<WeaponType::Guns, WeaponBase>, 
 boost::_bi::list1<boost::_bi::value<WeaponBase*> > > const&, WeaponType::Guns)'

1 个答案:

答案 0 :(得分:1)

如果您无法按照自己的意愿工作boost::bind,可以尝试使用Boost.Pheonix或Boost.Lamda作为解决方法。

尝试使用boost::pheonix::bind(来自Boost.Pheonix)代替boost::bind

#include <boost/phoenix/operator.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
#include <boost/function.hpp>
#include <iostream>

enum WeaponType {melee, ranged, special};

class Sword
{
public:
    WeaponType GetType() const {return melee;}

    void test()
    {
        namespace bp = boost::phoenix;
        boost::function<bool()> isSpecialWeapon =
            bp::bind(&Sword::GetType, this) == special;
        std::cout << "isSpecialWeapon() = " << isSpecialWeapon() << "\n";
    }

};

int main()
{
    Sword sword;
    sword.test();
}

或者,您也可以使用boost::lambda::bind(来自Boost.Lambda):

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

enum WeaponType {melee, ranged, special};

class Sword
{
public:
    WeaponType GetType() const {return melee;}

    void test()
    {
        boost::function<bool()> isSpecialWeapon =
            boost::lambda::bind(&Sword::GetType, this) == special;
        std::cout << "isSpecialWeapon() = " << isSpecialWeapon() << "\n";
    }

};

int main()
{
    Sword sword;
    sword.test();
}