msgmaxim
msgmaxim

Reputation: 818

How do I pass a variable to a function object?

In the examlpe below I need to define a function to compare my objects using certain rules in getHappiness(Animal*) method. The method cannot be static and rather complicated. I need a pointer in the comparison definition to call getHappiness method.

So my question is: how do I pass a pointer to this method, it gets called automatically when I insert an element into the map. And also it doesn't seem that I can instantiate Compare structure and pass the pointer to the constructor.

Am I doing anything wrong? Maybe there is an alternative way to how I define a comparison function?

struct Compare {bool operator()(Animal* const, Animal* const) const;}; 

bool
Compare::operator()(Animal* const a1, Animal* const a2) const {

  Zoo* zoo; // somehow I need to get access to the Zoo instance here

  if (zoo->getHappiness(a1) > zoo->getHappiness(a2)) return true;
  return false;
}

Class Zoo(){
  std::multimap<Animal*, Man*, Compare> map;

  int getHappiness(Animal*); // cannot be static

}

int main(){
...
  Zoo zoo;
  zoo.map.insert(...);
...
}

Upvotes: 0

Views: 84

Answers (1)

billz
billz

Reputation: 45470

There is a design issue in your code. Happiness should be an attribute which belong to an animal not a zoo. So implement getHappiness() on animal makes your code much simpler:

struct Compare 
{
    bool operator()(Animal& const, Animal& const) const;
}; 

bool Compare::operator()(Animal& const a1, Animal& const a2) const 
{
    return a1.getHappiness() < a2.getHappiness();
}

Class Zoo(){
  std::multimap<Animal, Man, Compare> map;

}

Also, if not necessary, don't use pointer. If you can't avoid pointer, use smart pointer in STL container.

Upvotes: 1

Related Questions