3 Function objects
This chapter covers
- Different things that can be used as functions in C++
- Creating generic function objects
- What lambdas are, and how they relate to ordinary function objects
- Creating prettier function objects with the Boost.Phoenix library and by hand
- What
std::function
is and when to use it
You saw how to create functions that can accept other functions as their arguments in the previous chapter. Now you’ll check out the other side of the coin—to see all the things that you can use as functions in C++. This topic is a bit dry, but it’s necessary for the deeper understanding of functions in C++ and for achieving that sweet spot of using higher-level abstractions without incurring performance penalties. If you want to be able to use all the power that C++ gives you during your functional programming adventures, you need to know all the things that C++ can treat as functions—and which of them to prefer, and which of them to avoid.
Using duck-typing (if it walks like a duck and quacks like a duck, it’s a duck), we can say that anything that can be called like a function is a function object. Namely, if we can write the name of an entity followed by arguments in parentheses, such as f(arg1, arg2, …, argn)
, that entity is a function object. We’ll cover all the things that C++ considers to be function objects in this chapter.