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

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.

主站蜘蛛池模板: 永州市| 利川市| 湖口县| 城口县| 丹棱县| 镇沅| 扬州市| 东乌珠穆沁旗| 沂水县| 勃利县| 永登县| 田东县| 临泽县| 娱乐| 调兵山市| 兴国县| 海晏县| 双城市| 扶风县| 贡嘎县| 丹凤县| 武城县| 东至县| 南京市| 衡水市| 织金县| 秦皇岛市| 昌黎县| 凤凰县| 绥中县| 宝丰县| 炉霍县| 海林市| 四会市| 高雄市| 抚远县| 呼伦贝尔市| 康马县| 澄城县| 牙克石市| 临城县|