Advertisement
Guest User

Untitled

a guest
Oct 17th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4.  
  5. using namespace std;
  6.  
  7. // Перерузка в структуре
  8. struct {
  9.     int call(int a, int b) {
  10.         return a + b;
  11.     }
  12.  
  13.     double call(double a, double b) {
  14.         return a + b;
  15.     }
  16. } foo;
  17.  
  18. // Обычная перегрузка
  19. int call(int a, int b) {
  20.     return a + b;
  21. }
  22.  
  23. double call(double a, double b) {
  24.     return a + b;
  25. }
  26.  
  27. //  Шаблонная функция
  28. template<typename T>
  29. T call2(T a, T b) {
  30.     return a + b;
  31. }
  32.  
  33.  
  34. // Шаблонный std::function
  35. template<typename T>
  36. void reduce1(vector<int> a, vector<double> b,
  37.             std::function<T(T, T)> func)
  38. {
  39.     int lastStepI = 0;
  40.     for(int x : a)
  41.     {
  42.         lastStepI = func(lastStepI, x);
  43.     }
  44.  
  45.     cout << lastStepI << endl;
  46.  
  47.     double lastStepD = 0;
  48.     for(double x : b)
  49.     {
  50.         lastStepD = func(lastStepD, x);
  51.     }
  52.  
  53.     cout << lastStepD << endl;
  54. }
  55.  
  56. // Явное указание типов std::function
  57. void reduce2(vector<int> a, vector<double> b,
  58.             std::function<int(int,int)> funca,
  59.             std::function<double(double,double)> funcb)
  60. {
  61.     int lastStepI = 0;
  62.     for(int x : a)
  63.     {
  64.         lastStepI = funca(lastStepI, x);
  65.     }
  66.  
  67.     cout << lastStepI << endl;
  68.  
  69.     double lastStepD = 0;
  70.     for(double x : b)
  71.     {
  72.         lastStepD = funcb(lastStepD, x);
  73.     }
  74.  
  75.     cout << lastStepD << endl;
  76. }
  77.  
  78. // Через шалобнный тип
  79. template<typename Func>
  80. void reduce3(vector<int> a, vector<double> b, Func func)
  81. {
  82.     int lastStepI = 0;
  83.     for(int x : a)
  84.     {
  85.         lastStepI = func.call(lastStepI, x);
  86.     }
  87.  
  88.     cout << lastStepI << endl;
  89.  
  90.     double lastStepD = 0;
  91.     for(double x : b)
  92.     {
  93.         lastStepD = func.call(lastStepD, x);
  94.     }
  95.  
  96.     cout << lastStepD << endl;
  97. }
  98.  
  99.  
  100. int main()
  101. {
  102.     vector<int> a{1, 2, 3, 4, 5};
  103.     vector<double> b{1.1, 2.2, 3.3, 4.4, 5.5};
  104.  
  105.     reduce3(a, b, foo);
  106. //    reduce1(a, b, call); // Ошибка: no matching function for call to 'reduce1'
  107. //    reduce2(a, b, call, call); // Ошибка: no matching function for call to 'reduce2'
  108.     reduce2(a, b, call2<int>, call2<double>);
  109.  
  110.     return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement