wrapped2.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // wrapped2.cpp -- callable types and templates
  2. #include <iostream>
  3. #include <math.h>
  4. #include <functional>
  5. using namespace std;
  6. template <typename T>
  7. T use_f(T v, std::function<T(T)> 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. cout << "Function pointer dub:\n";
  35. cout << " " << use_f<double>(y, dub) << endl;
  36. cout << "Function pointer sqrt:\n";
  37. cout << " " << use_f<double>(y, sqrt) << endl;
  38. cout << "Function object Fp:\n";
  39. cout << " " << use_f<double>(y, Fp(5.0)) << endl;
  40. cout << "Function object Fq:\n";
  41. cout << " " << use_f<double>(y, Fq(5.0)) << endl;
  42. cout << "Lambda expression 1:\n";
  43. cout << " " << use_f<double>(y, [](double u) {return u*u;}) << endl;
  44. cout << "Lambda expression 2:\n";
  45. cout << " " << use_f<double>(y, [](double u) {return u+u/2.0;}) << endl;
  46. cin.get();
  47. return 0;
  48. }