Boost::bind重载操作符导致Boost未定义引用错误

Boost undefined reference error with boost::bind overloaded operators

本文关键字:Boost 未定义 错误 引用 操作符 bind 重载      更新时间:2023-10-16

所讨论的代码:

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)'

如果您不能让boost::bind按您的愿望工作,您可以尝试Boost。凤凰或Boost。

尝试使用boost::pheonix::bind(来自boost . phoenix)代替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();
}