Search code examples
c++boostboost-bind

How to convert a function that returns a int to a function that returns a bool using boost::bind?


I have something like the following:

 struct A{
  virtual int derp(){ 
      if(herp()) return 1; 
      else return 0; 
   }
  void slurp(){
    boost::function<bool(int x, int y)> purp = /** boost bind derp to match lvalue sig  **/;
  }
 }

Any ideas? I want to create the function prup which basically calls derp and ignores the (x,y) passed in.

I need something like

bool purp(int x, int y){ return derp(); }

but want to avoid creating it as a member function, and rather just create it locally if possible?


Solution

  • If C++11 is available, consider using a lambda. Otherwise, you can use Boost.Lambda:

    boost::function<bool(int x, int y)> purp = !!boost::lambda::bind(&A::derp, this);
    

    That uses the standard conversion of int to bool.

    If you want a specific return value of A::derp to be true, then use ==. For example, suppose you want a return value of 3 to be true:

    boost::function<bool(int x, int y)> purp = boost::lambda::bind(&A::derp, this) == 3;
    

    EDIT: Complete example:

    #include <iostream>
    
    #include <boost/function.hpp>
    #include <boost/lambda/lambda.hpp>
    #include <boost/lambda/bind.hpp>
    
    struct A {
        virtual int derp() {
            std::cout << "within A::derp()\n";
            return 0;
        }
        void slurp() {
            boost::function<bool(int x, int y)> purp = !!boost::lambda::bind(&A::derp, this);
            std::cout << (purp(3, 14) ? "true" : "false") << '\n';
        }
    };
    
    int main()
    {
        A a;
        a.slurp();
    }
    

    Outputs:

    within A::derp()
    false