1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <iostream>
#include <string>
#include <functional>
#include <set>
#include <vector>
#include <iterator>
class foo1
{
int data1;
double data2;
public:
foo1(int d1, double d2) : data1(d1), data2(d2) {}
void operator () ()
{
std::cout << "foo1 data1 = " << data1 << ", data2 = " << data2 << std::endl;
}
};
class foo2
{
std::string data;
public:
foo2(std::string d) : data(d) {}
void operator () ()
{
std::cout << "foo2 data1 = " << data << std::endl;
}
};
class foo3
{
float data1;
std::string data2;
int data3;
public:
foo3(float d1, std::string d2, int d3) : data1(d1), data2(d2), data3(d3) {}
void operator () ()
{
std::cout << "foo3 data1 = " << data1 << ", data2 = " << data2 << ", data3 = " << data3 << std::endl;
}
};
class foo4
{
public:
foo4() {}
void operator () ()
{
std::cout << "foo4" << std::endl;
}
};
typedef std::function<void()> tFun;
bool compareFunction(const tFun &tf1, const tFun &tf2)
{
return &tf1 < &tf2;
}
int main()
{
foo1 f1(3, 8.5);
foo2 f2("hello");
foo3 f3(2.8f, "doo", 4);
foo4 f4;
#if true // use set
std::clog << "USING SET" << std::endl;
// C++98 style
//std::set<tFun, bool (*)(const tFun &tf1, const tFun &tf2)> sFun(compareFunction);
// C++11 style
std::set<tFun, bool (*)(const tFun &tf1, const tFun &tf2)> sFun([](const tFun &tf1, const tFun &tf2) -> bool {
return &tf1 < &tf2;
});
sFun.insert(f1);
sFun.insert(f3);
sFun.insert(f2);
sFun.insert(f4);
#else // use vector
std::clog << "USING VECTOR" << std::endl;
std::vector<tFun> sFun;
sFun.push_back(f1);
sFun.push_back(f2);
sFun.push_back(f3);
sFun.push_back(f4);
#endif
auto it = sFun.begin();
const auto& end = sFun.end();
for(; it != end; ++it)
{
(*it)();
}
return 0;
}
|