xxar3s

Bindovanie z std::function

Sep 26th, 2020
82
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4.  
  5. template<typename T>
  6. void dump(std::vector<T> keys)
  7. {
  8.     std::wcout << L"Keys: [";
  9.     auto isFirst = true;
  10.     for (auto key : keys)
  11.     {
  12.         std::wcout << (isFirst ? L"" : L", ") << key;
  13.         isFirst = false;
  14.     }
  15.     std::wcout << L"]" << std::endl;
  16. }
  17.  
  18. template<typename T1, typename T2> using Mapper = std::function<T2(T1 item)>;
  19.  
  20. template<typename T1, typename T2>
  21. std::vector<T2> map(const Mapper<T1, T2> mapper, const std::vector<T1> vec)
  22. {
  23.     std::vector<T2> result;
  24.     for (T1 x : vec)
  25.     {
  26.         result.push_back(mapper(x));
  27.     }
  28.     return result;
  29. }
  30.  
  31. using namespace std::placeholders;
  32. auto func = [](int n, int m)
  33. {
  34.     return n * m;
  35. };
  36.  
  37. int main()
  38. {
  39.     auto multiplier = 5;
  40.     std::function<int(int)> mapper = std::bind(func, _1, multiplier);
  41.     auto list = map<int, int>(
  42.         mapper,
  43.         { 1, 2, 3 }
  44.     );
  45.     dump<int>(list);
  46. }
RAW Paste Data