14.8. Function-Call Operator

Image

Classes that overload the call operator allow objects of its type to be used as if they were a function. Because such classes can also store state, they can be more flexible than ordinary functions.

As a simple example, the following struct, named absInt, has a call operator that returns the absolute value of its argument:

struct absInt {    int operator()(int val) const {        return val < 0 ? -val : val;    }};

This class defines a single operation: the function-call operator. That operator takes an argument of type int and returns the argument’s absolute value.

We use the call operator by applying an argument ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.