/docs/MyDocs

To get this branch, use:
bzr branch http://darksoft.org/webbzr/docs/MyDocs

« back to all changes in this revision

Viewing changes to Development/languages/C/Samples.CPP/functor.cpp

  • Committer: Suren A. Chilingaryan
  • Date: 2009-04-09 03:21:08 UTC
  • Revision ID: csa@dside.dyndns.org-20090409032108-w4edamdh4adrgdu3
import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <iostream>
 
2
#include <vector>
 
3
#include <string>
 
4
 
 
5
/* STL algorithms that take a function argument don't care whether it's a real 
 
6
function, a member function, or a function object, so long as they can use the 
 
7
notation f() to call it. The problem is that you can't call a member function 
 
8
directly; you need to call it for a pointer or an object */
 
9
 
 
10
using namespace std;
 
11
 
 
12
template <class T> int func(T &val) {
 
13
    cout << val << endl;
 
14
};
 
15
 
 
16
 
 
17
class DataClass {
 
18
 public:
 
19
    DataClass(const char *ch) {
 
20
        str = ch;
 
21
    }
 
22
    
 
23
    void func() {
 
24
        cout << str << endl;
 
25
    }
 
26
    
 
27
 private:
 
28
    string str;
 
29
 
 
30
};
 
31
 
 
32
 
 
33
class MyClass {
 
34
 public:
 
35
    MyClass(string pref) {
 
36
        prefix = pref;
 
37
    }
 
38
    
 
39
    void operator ()(string &val) {
 
40
        cout << prefix << val << endl;
 
41
    }
 
42
 private:
 
43
    string prefix;    
 
44
};
 
45
 
 
46
 
 
47
main() {
 
48
    vector<string> v;
 
49
    
 
50
        /* Calling just a function with elements as an argument */
 
51
    v.push_back("1");
 
52
    v.push_back("2");
 
53
    for_each(v.begin(), v.end(), func<string>);
 
54
    
 
55
 
 
56
        /* Calling a method from element objects
 
57
            mem_fun_ref() function binds the class function with a reference to
 
58
            object allowing to call object method. 
 
59
            
 
60
            Also exists mem_fun doest the same for pointers
 
61
        */
 
62
    vector<DataClass> v1;
 
63
    v1.push_back("1");
 
64
    v1.push_back("2");
 
65
    for_each(v1.begin(), v1.end(), mem_fun_ref(&DataClass::func));
 
66
 
 
67
 
 
68
        /* Calling functor */
 
69
    for_each(v.begin(), v.end(), MyClass("prefix: "));
 
70
    
 
71
    
 
72
}