Re: operator (), what is it?
[Please do not mail me a copy of your followup]
Doug Mika <dougmmika@gmail.com> spake the secret code
<ea2187b1-aced-4be3-bc0e-1d7854639d49@googlegroups.com> thusly:
Hi to all, I was wondering what overloading the operator() is?
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?
The standard library often has algorithms that take predicates as
arguments. For instance, std::list::remove_if takes a UnaryPredicate
argument <http://en.cppreference.com/w/cpp/container/list/remove>:
"template <class UnaryPredicate>
void remove_if(UnaryPredicate p);
Removes all elements satisfying specific criteria [...]
removes all elements for which predicate p returns true."
The argument p is a model of UnaryPredicate, a function that can be
called like:
bool pred(int a);
for a std::list<int>. You can supply a predicate function in many
ways, such as:
1) a pointer to a function
bool is_odd(int a) { return (a % 2) == 1; }
// ...
mylist.remove_if(is_odd);
2) a lambda function
my_list.remove_if([](int a) { return (a % 2) == 1; });
3) a function object
struct is_odd {
bool operator()(int a) { return (a % 2) == 1; }
};
my_list.remove_if(is_odd());
4) some other expression for which 'pred(a)' is well defined and
returns a bool:
bool remainder_is_one(int b, int a) { return (a % b) == 1; }
my_list.remove_if(std::bind(remainder_is_one, 2));
One of the reasons for introducing lambdas into the language was to
simplify the use of such "function objects", particularly when they
are simple expressions such as "is this an odd integer".
In your example code, the predicate passed to remove_if was an
anonymous instance of the struct is_odd that overrode the function
call operator with a single argument. (In my examples, I wrote the
argument declaration as 'int a', instead of 'const int &a', since it
isn't useful to pass integers by const reference.)
mylist.remove_if (single_digit); // 15 36 17 20 39
This uses a pointer to the function single_digit.
mylist.remove_if (is_odd()); // 36 20
This uses an anonymous (unnamed) instance of the struct is_odd.
Remember also that the primary difference between struct and class is
that class has private visibility by default and struct has public
visibility by default. Anything you can do with a class you can also
do with a struct.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>