0

It seems to be stupid question but I have never seen something like this!

int operator() (const std::string& s1, const std::string& s2) const

to me operator is a const member function that return an intger and no variable argument! but need two const variables s1 and s2?!?! I can't get the point of this!

class str_dist_ : 
public std::binary_function<std::string, std::string, int> {
public:
  int op() (const std::string& s1, const std::string& s2) const
  {
    if (s1 == s2)
      return 0;
    else if (s1.empty())
      return std::max(s2.size()/2, 1u);
    else if (s2.empty())
      return std::max(s1.size()/2, 1u);
    else 
      return min_edit_distance(s1, s2, zero_one_cost<char>(' '));
  }
  std::string empty() const { return std::string(); }
};
Adam Mitz
  • 6,025
  • 1
  • 29
  • 28
Yasaman
  • 61
  • 2
  • 11

3 Answers3

3

The operator() part says that objects of type str_dist_ can be "called", as though it were a function. The (const std::string& s1, const std::string& s2) tells us what the argument actually are.

For example, say we have an object str_dist_ obj;, and two std::string objects, str1 and str2. Then we can write something like this

int result = obj(str1, str2);

Under the covers, the previous line is identical to

int result = obj.operator()(str1, str2);

Notice that the first set of parenthesis are part of the name of the member function operator(), while the second set actually lists the arguments.

If you want more information, look up Functors or Function Objects. These are the terms used to refer to things such as str_dist_ objects, which have the operator() defined for them. If you google either of those terms, you're sure to find a lot of information.

Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
2

It's the parenthesis-operator (or "function-call operator"):

Foo x;
int n = x(12, 'a');
int m = x.operator()(12, 'a'); // equivalent

Here the operator was declared as int Foo::operator()(int, char).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

It's the "function call operator", it allows an object to be used "as a function", i.e.:

str_dist_ myObject;
cout<<myObject("A string", "Another string"); // calls operator()

The first two parentheses denote that it's the function call operator (as the + would denote that it's the + operator, etc.), then follows the arguments list.

The whole point of overloading the function call operator is to create functors (function objects), that have several advantages over plain functions.

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299