Re: operator (), what is it?
On 4/13/2015 1:35 PM, Doug Mika wrote:
Hi to all, I was wondering what overloading the operator() is?
It's called "operator function call". What book are you reading that
does not explain it?
I know that overloading an operator< allows for the direct
comparison
of my two objects using <, but what about the operator(), especially in
a struct? Does it allow the struct to be called like a function?
// list::remove_if
#include <iostream>
#include <list>
// a predicate implemented as a function:
bool single_digit (const int& value) { return (value<10); }
// a predicate implemented as a class:
struct is_odd {
bool operator() (const int& value) { return (value%2)==1; }
};
int main ()
{
int myints[]= {15,36,7,17,20,39,4,1};
std::list<int> mylist (myints,myints+8); // 15 36 7 17 20 39 4 1
mylist.remove_if (single_digit); // 15 36 17 20 39
mylist.remove_if (is_odd()); // 36 20
That's a call to the template function 'remove_if' and providing a
temporary object as its argument. You need to understand what
'remove_if' does in order to comprehend this fully. Step into it using
your debugger, and take a good look at the code.
std::cout << "mylist contains:";
for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Predicates designed to work with standard functions like 'for_each',
'copy_if', etc., need to provide a special member function - the
operator function call, with a particular argument number and types.
Get yourself a decent book on C++ and read it. Daily.
V
--
I do not respond to top-posted replies, please don't ask