1

I am not able to understand this piece of code from GeeksforGeeks:

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Comparison function for sorting the
// set by increasing order of its pair's
// second value
struct comp {
    template <typename T>
  
    // Comparator function
    bool operator()(const T& l,
                    const T& r) const
    {
        if (l.second != r.second) {
            return l.second < r.second;
        }
        return l.first < r.first;
    }
};

I find similar article in StackOverflow. but all of them are little different.

I also want to ask, what is the difference between writing bool operator () and operator bool()?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Shizu
  • 124
  • 1
  • 2
  • 7
  • 3
    `bool operator()` is a function operator, making the instantiated object a *functor*. But `operator bool()` is an implicit conversion operator converting the object to `bool`. – Eljay May 25 '21 at 20:02
  • 6
    Note that [`#include ` is an awful habit](https://stackoverflow.com/q/31816095/10077), as is [`using namespace std;`](https://stackoverflow.com/q/1452721/10077). Combining them is pretty much begging for problems. – Fred Larson May 25 '21 at 20:07
  • 2
    @FredLarson GeeksForGeeks is awful for that, and lots of beginned fall into the trap of trusting that site that share bad practices. – Guillaume Racicot May 25 '21 at 20:08
  • @GuillaumeRacicot: Yes, so I've gathered. – Fred Larson May 25 '21 at 20:09

1 Answers1

4

bool operator() defines the operator () for the class instances and makes it accept two arguments to make a comparison and return a bool.

While operator bool() defines the bool operator i.e makes the class instances be convertible to bools


As a summary, the first function overloads the operator () while the second overloads the operator bool


An example

Suppose you want to define a comparator and want to know if it's valid or not so you put a flag to know that, hence you have the following.

struct Comparator{
    bool valid{};
    template<class T>
    bool operator()(const T& lhs, const T& rhs)const{
        return lhs<rhs;
    }
    explicit operator bool()const{
        return valid;
    }
};

int main(){
    Comparator x{true};
    std::cout <<((x) ? "x is valid": "x is not valid") << "\n";
    std::cout << "is 1 les than 2: " << std::boolalpha <<  x(1,2);
}

It's not a good use case but I wanted to put both operators in one class to say that they can be defined for the same class.

The bool operator is used with the objects that may be in an invalid state like smart pointers and std::optional<T> ,...

asmmo
  • 6,922
  • 1
  • 11
  • 25