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

StackOverflow https://stackoverflow.com/questions/13829824

  •  07-12-2021
  •  | 
  •  

Question

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?

Was it helpful?

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

OTHER TIPS

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

This should work as long as derp return value is implicitly convertible to bool. You will get this annoying warning with VC++ though: "warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)"

I am not really sure about the boost::bind library and how to handle your case, but if you have a C++ enabled environment you can use a lambda in place of the bind:

auto purp = [=](int,int) -> bool { return derp(); };
// alternatively:
//std::function<bool(int,int)> purp = [](int,int)->bool{return derp();};

With lambda support suddenly bind does not seem like such a great tool :)

Boolean true/false is just an integer in C implementations already and you could certainly write something to do this. I do not understand the point of doing this or why the function is contained in a struct. The main question is why would you want a function to take parameters so they can be ignored ? Why not have the function return a bool instead of an int ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top