Studying STL I have tried to negate a functor with not2 but encontered problems.
Here is the example:
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
struct mystruct : binary_function<int,int,bool> {
bool operator() (int i,int j) { return i<j; }
};
template <class T>
class generatore
{
public:
generatore (T start = 0, T stp = 1) : current(start), step(stp)
{ }
T operator() () { return current+=step; }
private:
T current;
T step;
};
int main () {
vector<int> first(10);
generate(first.begin(), first.end(), generatore<int>(10,10) );
cout << "Smallest element " << *min_element(first.begin(), first.end(),mystruct() ) << endl;
cout << "Smallest element: " << *max_element(first.begin(), first.end(),not2(mystruct())) << endl;
}
Last line of code wil not compile using g++. Probably a stupid error but where ?
Change:
too:
There are two implicit question on your question in the comments:
1) Why should I add const to the method:
You should use const as no members of the object are changed.
Creating methods const correct is easy. Adding const correctness to methods after the fact can become a real nighmare as the const propogates further and further into your class hierarchy.
2) Why adding const to the method makes it compile.
The constructor of the object returned by not2() is taking a const reference to your object as a parameter. This is a relatively common technique, but does require that any methods that you use are also const.