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

  • Mastering C++ Programming
  • Jeganathan Swaminathan
  • 161字
  • 2021-07-02 18:28:48

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.

主站蜘蛛池模板: 东阳市| 东明县| 江源县| 万安县| 哈巴河县| 泾川县| 柳河县| 都昌县| 正宁县| 丰镇市| 武威市| 灌云县| 周至县| 怀仁县| 青阳县| 大英县| 梅州市| 潞城市| 临沧市| 马公市| 铜鼓县| 江山市| 濉溪县| 达拉特旗| 浮山县| 平顺县| 南木林县| 泾源县| 中宁县| 昆明市| 凤冈县| 三门县| 西和县| 玛曲县| 冷水江市| 鄂尔多斯市| 基隆市| 镇雄县| 枝江市| 卓尼县| 逊克县|