Question

#include <boost/ref.hpp>
//#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/mem_fn.hpp>

using namespace std;
using namespace boost::lambda;

class Base {
  public:
  Base () {}
  bool toBeRemoved() const {
    return true;
  }
};

class status : public Base {
  std::string name_;
  bool ok_;
public:
  status(const std::string& name):name_(name),ok_(true) {}

  void break_it() {
    ok_=false;
  }

  bool is_broken() const {
    return ok_;
  }

  void report() const {
    std::cout << name_ << " is " <<
      (ok_ ? "working nominally":"terribly broken") << '\n';
  }
  std::string getStatus() const {
    return ok_ ? "1" : "0";
  }
};

class some_class {
 public:
 int test() {
   std::vector<boost::shared_ptr<status> > s_statuses = getStatus(); //some func 
   std::set<string> s;
   std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::lambda::bind(boost::mem_fn(&status::getStatus), boost::ref(*_1)));

// approach #2
//   std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::lambda::bind(boost::mem_fn(&status::getStatus), boost::ref(*_1), _1));

// approach #3
//   std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), boost::bind(&status::getStatus), _1));

   std::copy(s.begin(), s.end(), ostream_iterator<string>(std::cout, "-"));
   std::cout << endl;
   return 0;
 }
}

For all the approaches above, I am getting the error "can call member function without object" on the line containing the bind call. I have tried using boost::lambda::bind and boost::bind as well. Though this way of using bind works if objects are defined, for example in main function. I assume I am making some silly mistake here, but I am not able to figure out why these all approaches working, or it could be the case that this is not the right way of doing at all. Could someone please help me resolve this on how to properly use boost bind for non-static member of class which are stored in stl containers ?

Thanks,

Was it helpful?

Solution

You should just need to use boost::mem_fn. (Note, you could also use std::mem_fn if available.)

std::transform(s_statuses.begin(), s_statuses.end(), std::inserter(s, s.begin()), std::mem_fn(&status::getStatus));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top