Function Objects
At first, don’t call them functors. That’s a well-defined term from the category theory.
Function objects are objects that behave like functions. They achieve this due to their call operator being implemented. As functions objects are objects, they can have attributes and therefore state.
struct
Square
{
void
operator
()(
int
&
i
){
i
=
i
*
i
;}
};
std
::
vector
<
int
>
myVec
{
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
};
std
::
for_each
(
myVec
.
begin
(),
myVec
.
end
(),
Square
());
for
(
auto
v
:
myVec
)
std
::
cout
<<
v
<<
" "
;
// 1 4 9 16 25 36 49 64 81 100