Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <functional>
- using namespace std;
- // Перерузка в структуре
- struct {
- int call(int a, int b) {
- return a + b;
- }
- double call(double a, double b) {
- return a + b;
- }
- } foo;
- // Обычная перегрузка
- int call(int a, int b) {
- return a + b;
- }
- double call(double a, double b) {
- return a + b;
- }
- // Шаблонная функция
- template<typename T>
- T call2(T a, T b) {
- return a + b;
- }
- // Шаблонный std::function
- template<typename T>
- void reduce1(vector<int> a, vector<double> b,
- std::function<T(T, T)> func)
- {
- int lastStepI = 0;
- for(int x : a)
- {
- lastStepI = func(lastStepI, x);
- }
- cout << lastStepI << endl;
- double lastStepD = 0;
- for(double x : b)
- {
- lastStepD = func(lastStepD, x);
- }
- cout << lastStepD << endl;
- }
- // Явное указание типов std::function
- void reduce2(vector<int> a, vector<double> b,
- std::function<int(int,int)> funca,
- std::function<double(double,double)> funcb)
- {
- int lastStepI = 0;
- for(int x : a)
- {
- lastStepI = funca(lastStepI, x);
- }
- cout << lastStepI << endl;
- double lastStepD = 0;
- for(double x : b)
- {
- lastStepD = funcb(lastStepD, x);
- }
- cout << lastStepD << endl;
- }
- // Через шалобнный тип
- template<typename Func>
- void reduce3(vector<int> a, vector<double> b, Func func)
- {
- int lastStepI = 0;
- for(int x : a)
- {
- lastStepI = func.call(lastStepI, x);
- }
- cout << lastStepI << endl;
- double lastStepD = 0;
- for(double x : b)
- {
- lastStepD = func.call(lastStepD, x);
- }
- cout << lastStepD << endl;
- }
- int main()
- {
- vector<int> a{1, 2, 3, 4, 5};
- vector<double> b{1.1, 2.2, 3.3, 4.4, 5.5};
- reduce3(a, b, foo);
- // reduce1(a, b, call); // Ошибка: no matching function for call to 'reduce1'
- // reduce2(a, b, call, call); // Ошибка: no matching function for call to 'reduce2'
- reduce2(a, b, call2<int>, call2<double>);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement