fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. //macro overloading by number of arguments:
  7. //http://stackoverflow.com/a/11763277/556899
  8. #define GET_MACRO(_1, _2, _3, _4, _5, NAME, ...) NAME
  9. #define _L(...) GET_MACRO(__VA_ARGS__, _L4, _L3, _L2, _L1, _L0)(__VA_ARGS__)
  10.  
  11. //separate macro per each number of arguments
  12. #define _L0(res)\
  13.   [&]() { return res; }
  14. #define _L1(a, res)\
  15.   [&](auto a) { return res; }
  16. #define _L2(a, b, res)\
  17.   [&](auto a, auto b) { return res; }
  18. #define _L3(a, b, c, res)\
  19.   [&](auto a, auto b, auto c) { return res; }
  20. #define _L4(a, b, c, d, res)\
  21.   [&](auto a, auto b, auto c, auto d) { return res; }
  22.  
  23. //Swift-like version
  24. #define _S0(res) _L0(res)
  25. #define _S1(res) _L1(_0, res)
  26. #define _S2(res) _L2(_0, _1, res)
  27. #define _S3(res) _L3(_0, _1, _2, res)
  28. #define _S4(res) _L4(_0, _1, _2, _3, res)
  29.  
  30. int main() {
  31. auto f = [&](auto x, auto y) { return x + y; };
  32. cout << f(1, 4) << endl;
  33.  
  34. auto g = _L(x, y, x + y);
  35. cout << g(2, 5) << endl;
  36. auto x = _L(g(123, 321));
  37. cout << x() << endl;
  38. auto avg = _L(x, y, z, (x+y+z)/3.0);
  39. cout << avg(1, 2, 7) << endl;
  40.  
  41. vector<string> arr{"hello", "q", "any", "length", "gg", "omg"};
  42. auto compByKey = _L(f, _L(x, y, f(x) < f(y)));
  43. sort(arr.begin(), arr.end(), compByKey(_L(x, x.length())));
  44. for_each(arr.begin(), arr.end(), _L(x, (void)(cout << x << endl)));
  45.  
  46. sort(arr.begin(), arr.end(), _S2(_0 > _1));
  47. for_each(arr.begin(), arr.end(), _S1((void)(cout << _0 << endl)));
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
5
7
444
3.33333
q
gg
any
omg
hello
length
q
omg
length
hello
gg
any