Guest User

Untitled

a guest
May 23rd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. void add1(int &v)
  4. {
  5. v+=1;
  6. }
  7.  
  8. void add2(int &v)
  9. {
  10. v+=2;
  11. }
  12.  
  13. template <void (*T)(int &)>
  14. void doOperation()
  15. {
  16. int temp=0;
  17. T(temp);
  18. std::cout << "Result is " << temp << std::endl;
  19. }
  20.  
  21. int main()
  22. {
  23. doOperation<add1>();
  24. doOperation<add2>();
  25. }
  26.  
  27. struct add3 {
  28. void operator() (int &v) {v+=3;}
  29. };
  30. ...
  31.  
  32. doOperation<add3>();
  33.  
  34. template <typename F>
  35. void doOperation(F f)
  36. {
  37. int temp=0;
  38. f(temp);
  39. std::cout << "Result is " << temp << std::endl;
  40. }
  41.  
  42. doOperation(add2);
  43. doOperation(add3());
  44.  
  45. template <void (*T)(int &)>
  46. void doOperation()
  47.  
  48. template <class T>
  49. void doOperation(T t)
  50. {
  51. int temp=0;
  52. t(temp);
  53. std::cout << "Result is " << temp << std::endl;
  54. }
  55.  
  56. template<typename OP>
  57. int do_op(int a, int b, OP op)
  58. {
  59. return op(a,b,);
  60. }
  61. int add(int a, b) { return a + b; }
  62. ...
  63.  
  64. int c = do_op(4,5,add);
  65.  
  66. int (* func_ptr)(int, int) = add;
  67. int c = do_op(4,5,func_ptr);
  68.  
  69. int (* func_ptr)(int,int) = add;
  70. int c = do_op<func_ptr>(4,5);
  71.  
  72. template<typename OP>
  73. int do_op(int a, int b, OP op) { return op(a,b); }
  74. float fadd(float a, float b) { return a+b; }
  75. ...
  76. int c = do_op(4,5,fadd);
  77.  
  78. convert a and b from int to float.
  79. call the function ptr op with float a and float b.
  80. convert the result back to int and return it.
  81.  
  82. struct Square
  83. {
  84. double operator()(double number) { return number * number; }
  85. };
  86.  
  87. template <class Function>
  88. double integrate(Function& f, double a, double b, unsigned int intervals)
  89. {
  90. double delta = (b - a) / intervals, sum = 0.0;
  91.  
  92. while(a < b)
  93. {
  94. sum += f(a) * delta;
  95. a += delta;
  96. }
  97.  
  98. return sum;
  99. }
  100.  
  101. std::cout << "interval : " << i << tab << tab << "intgeration = "
  102. << integrate(Square(), 0.0, 1.0, 10) << std::endl;
Add Comment
Please, Sign In to add comment