callable.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // callable.cpp -- callable types and templates
  2. #include <iostream>
  3. #include <math.h>
  4. using namespace std;
  5. template <typename T, typename F>
  6. T use_f(T v, F f)
  7. {
  8. static int count = 0;
  9. count++;
  10. cout << " use_f count = " << count << ", &count = " << &count << endl;
  11. return f(v);
  12. }
  13. class Fp
  14. {
  15. private:
  16. double z_;
  17. public:
  18. Fp(double z = 1.0) : z_(z) {}
  19. double operator()(double p) { return z_*p; }
  20. };
  21. class Fq
  22. {
  23. private:
  24. double z_;
  25. public:
  26. Fq(double z = 1.0) : z_(z) {}
  27. double operator()(double q) { return z_+ q; }
  28. };
  29. double dub(double x) {return 2.0*x;}
  30. int main()
  31. {
  32. double y = 1.21;
  33. cout << "Function pointer dub:\n";
  34. cout << " " << use_f(y, dub) << endl;
  35. cout << "Function pointer sqrt:\n";
  36. cout << " " << use_f(y, sqrt) << endl;
  37. cout << "Function object Fp:\n";
  38. cout << " " << use_f(y, Fp(5.0)) << endl;
  39. cout << "Function object Fq:\n";
  40. cout << " " << use_f(y, Fq(5.0)) << endl;
  41. cout << "Lambda expression 1:\n";
  42. cout << " " << use_f(y, [](double u) {return u*u;}) << endl;
  43. cout << "Lambda expresson 2:\n";
  44. cout << " " << use_f(y, [](double u) {return u+u/2.0;}) << endl;
  45. cin.get();
  46. return 0;
  47. }