Tuesday, February 16, 2010

Function Object

In C++, we normally make class instance and call a method of the instance. However, there's a way to call class instance itself as a function like below.

 1 #include <iostream>
 2 #include <functional>
 3
 4 using namespace std;
 5
 6 class Sample
 7 {
 8     public:
 9         int operator() (int a, int b) const {
10             return a + b;
11         }
12 };
13
14 int main()
15 {
16     Sample s;
17     cout << s(1, 2) << endl;
18     return 0;
19 }


You can set input arguments information and return type like line 9 above. Function object is processed as an inline function, so it's fast than normal function call. And it is also useful when you want to set a status related to a certain function cause it's class so it can keep a value as a member.

No comments:

Post a Comment