- 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.
推薦閱讀
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- Python數據分析基礎
- PHP 7底層設計與源碼實現
- React Native Cookbook
- NativeScript for Angular Mobile Development
- 高級C/C++編譯技術(典藏版)
- Node Cookbook(Second Edition)
- 實戰Python網絡爬蟲
- Flask開發Web搜索引擎入門與實戰
- Getting Started with Web Components
- Koa與Node.js開發實戰
- Android從入門到精通
- PHP典型模塊與項目實戰大全
- Learning PrimeFaces Extensions Development
- C#多線程編程實戰