wrapped1.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //wrapped1.cpp -- using a function wrapper as an argument
  2. #include <iostream>
  3. #include <math.h>
  4. #include <functional>
  5. using namespace std;
  6. template <typename T, typename F>
  7. T use_f(T v, F f)
  8. {
  9. static int count = 0;
  10. count++;
  11. cout << " use_f count = " << count << ", &count = " << &count << endl;
  12. return f(v);
  13. }
  14. class Fp
  15. {
  16. private:
  17. double z_;
  18. public:
  19. Fp(double z = 1.0) : z_(z) {}
  20. double operator()(double p) { return z_*p; }
  21. };
  22. class Fq
  23. {
  24. private:
  25. double z_;
  26. public:
  27. Fq(double z = 1.0) : z_(z) {}
  28. double operator()(double q) { return z_+ q; }
  29. };
  30. double dub(double x) {return 2.0*x;}
  31. int main()
  32. {
  33. double y = 1.21;
  34. function<double(double)> ef1 = dub;
  35. function<double(double)> ef2 = sqrt;
  36. function<double(double)> ef3 = Fq(10.0);
  37. function<double(double)> ef4 = Fp(10.0);
  38. function<double(double)> ef5 = [](double u) {return u*u;};
  39. function<double(double)> ef6 = [](double u) {return u+u/2.0;};
  40. cout << "Function pointer dub:\n";
  41. cout << " " << use_f(y, ef1) << endl;
  42. cout << "Function pointer sqrt:\n";
  43. cout << " " << use_f(y, ef2) << endl;
  44. cout << "Function object Fp:\n";
  45. cout << " " << use_f(y, ef3) << endl;
  46. cout << "Function object Fq:\n";
  47. cout << " " << use_f(y, ef4) << endl;
  48. cout << "Lambda expression 1:\n";
  49. cout << " " << use_f(y, ef5) << endl;
  50. cout << "Lambda expression 2:\n";
  51. cout << " " << use_f(y,ef6) << endl;
  52. // cin.get();
  53. return 0;
  54. }