In modern C++ programming we can use many different ways to call functions. One of the features from C11 is functor, an early function object in C++. The functor function objects are callable objects. A functor or function object is any object for which the function call operator is defined. Let’s learn what a functor is and how we can use a functor in C++.
What is a functor in C++?
A functor is an object that can be used as a function or function pointer by using operator()
, this term is not same as function term in programming. We can pass many arguments with them; thus, we don’t need to define many global variables, we can use these kinds of variables in the scope that we use.
Here is the syntax how we can use define a functor by using function call operator operator()
,
1 2 3 |
return_type operator()( parameters ) |
Is there a simple example of how to run a functor object with std::thread in C++?
We can create operators as shown below in our simple functor example. This simple rectangle example function object returns its area as below.
1 2 3 4 5 6 7 8 9 10 11 12 |
class TRectangle { public: double Width=10, Height=10; double operator()() { return Width*Height; } }; |
in this example, we can use its initial values to calculate its area by using our functor like so:
1 2 3 4 5 |
TRectangle r1; r1(); |
Is there a full example of how to run a functor object with std::thread in C++?
Here is a full example of how to run a functor object with std::thread
in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> class TRectangle { public: double Width, Height; double operator()() { return Width*Height; } }; int main() { TRectangle r1; r1.Width = 20; r1.Height = 10; std::cout << "Area:" << r1() << std::endl; r1.Height = 20; std::cout << "Area:" << r1() << std::endl; system("pause"); return 0; } |
and the output will be as follows,
1 2 3 4 |
Area:200 Area:400 |
The function objects are callable objects, and they are enhanced by the new standard library features in C++17 (std::invoke
), C++20 (jthread
), C++23 (invoke_r
, move_only_function
) , and in the next C++26 (copyable_function
).
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.