官术网_书友最值得收藏!

Functors

Functors are objects that behave like regular functions. The beauty is that functors can be substituted in the place of function pointers. Functors are handy objects that let you extend or complement the behavior of an STL function without compromising the object-oriented coding principles.

Functors are easy to implement; all you need to do is overload the function operator. Functors are also referred to as functionoids.

The following code will demonstrate the way a simple functor can be implemented:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

template <typename T>
class Printer {
public:
void operator() ( const T& element ) {
cout << element << "\t";
}
};

int main () {
vector<int> v = { 10, 20, 30, 40, 50 };

cout << "\nPrint the vector entries using Functor" << endl;

for_each ( v.begin(), v.end(), Printer<int>() );

cout << endl;

return 0;
}

Let's quickly compile the program using the following command:

g++ main.cpp -std=c++17
./a.out

Let's check the output of the program:

Print the vector entries using Functor
10 20 30 40 50

We hope you realize how easy and cool a functor is.

主站蜘蛛池模板: 徐汇区| 柏乡县| 泸定县| 安乡县| 清原| 六枝特区| 松潘县| 平阴县| 张家口市| 隆化县| 方城县| 深圳市| 绥阳县| 马尔康县| 岳普湖县| 芮城县| 凌海市| 华容县| 新源县| 蓬溪县| 洱源县| 盈江县| 萍乡市| 垣曲县| 清新县| 乐清市| 缙云县| 宣化县| 高平市| 江西省| 泸溪县| 兴城市| 张掖市| 饶平县| 太原市| 神农架林区| 富裕县| 东阳市| 政和县| 上思县| 大新县|