Advertisement
quark_zju

cpp1y_experiment.cpp

Jul 25th, 2014
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. // compile with -std=c++1y
  2.  
  3. #include <iterator>
  4. #include <functional>
  5. #include <vector>
  6. #include <algorithm>
  7.  
  8. namespace LoDash {
  9.  
  10. using std::begin;
  11. using std::end;
  12. using std::vector;
  13. using std::function;
  14.  
  15. struct LoDash {
  16.   template<typename T>
  17.   auto _pure_typeof(T x) -> typename std::remove_const<typename std::remove_reference<decltype(x)>::type>::type { };
  18.  
  19.   template<typename L>
  20.   void each(const L& list, function<void(decltype(*begin(list))&)> iterator) {
  21.     for (auto& i: list) iterator(i);
  22.   }
  23.  
  24.   template<typename L>
  25.   size_t count(const L& list) {
  26.     return (size_t) std::distance(begin(list), end(list));
  27.   }
  28.  
  29.   template<typename V, typename L>
  30.   std::vector<V> map(const L& list, function<V(decltype(*begin(list)))> iterator) {
  31.     std::vector<V> result;
  32.     result.resize(count(list));
  33.     std::transform(begin(list), end(list), result.begin(), iterator);
  34.     return result;
  35.   }
  36.  
  37.   template<typename L>
  38.   auto map(const L& list, function<decltype(*begin(list))(decltype(*begin(list)))> iterator) -> std::vector<decltype(_pure_typeof(*begin(list)))> {
  39.     return map<decltype(_pure_typeof(*begin(list))), L>(list, iterator);
  40.   }
  41. };
  42.  
  43. }
  44.  
  45. auto _ = LoDash::LoDash();
  46.  
  47. #include <set>
  48. #include <iostream>
  49. #include <map>
  50.  
  51. using namespace std;
  52.  
  53. #define lambda [&]
  54.  
  55. int main(int argc, char const *argv[]) {
  56.   int a[] = {1, 2};
  57.   _.each(a, lambda (auto x) { std::cout << x << "\n"; });
  58.  
  59.   std::set<int> s = {3, 4};
  60.   _.each(s, lambda (auto x) { std::cout << x << "\n"; });
  61.  
  62.   std::vector<int> v = {5, 6};
  63.   _.each(v, lambda (auto x) { std::cout << x << "\n"; });
  64.  
  65.   auto m1 = _.map(v, lambda (auto x) { return -x; });
  66.   _.each(m1, lambda (auto x) { std::cout << x << "\n";});
  67.  
  68.   auto m2 = _.map<char>(v, lambda (int x) { return 'a' + x; });
  69.   _.each(m2, lambda (auto x) { std::cout << x << "\n";});
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement