Suppose we have an object which represent a box.
class Box {
public:
int length;
int width;
int height;
Box(int l, int w, int h);
~Box();
int area(const int l, const int w) const;
int volume(const int l, const int w, const int h) const;
};
Now lets say in another class, in another file, we have an std::list<Box> that contains n boxes. We want to display a print out of these boxes in different ways.
- First we want to print them out in order of increasing size by their lengths.
- Then we want to print them out in order of increasing size by their widths.
- We don’t care about their heights right now, but maybe later we will.
Now std::list has a member function sort() that takes a comparison function as an argument. How can we alter the above Box class so that we can call sort() on our list with different comparison functions?
More specifically, can we define three different functions inside the box class and simply pass them to list.sort()? Is it better to define the comparison functions globally outside of the class Intuitively, tying them to the class seems better but why would this not be the case? Overall, what is the “best” way to achieve this?
If you really want to implement the three different comparison
operations as members you can do something like this:
and use them like this:
mem_fun_refreturns an binary function object that takes a reference to the class of which the function is a member and all the rest of the arguments (only in C++11, this is limited to binary functions in C++03) of the member functions.Although it seems much more reasonable to implement the comparison
operations as free functions.