fork download
  1. #include <iostream>
  2. #include <cassert>
  3. #include <string>
  4. using namespace std;
  5.  
  6. auto identity = [](auto&& a) { return std::forward<decltype(a)>(a); };
  7.  
  8. auto compose = [](auto&& f, auto&& g) {
  9. return [f, g](auto&& val) { return f(g(std::forward<decltype(val)>(val))); };
  10. };
  11.  
  12. template<typename F, typename G>
  13. auto operator*(F&& f, G&& g) -> decltype(compose(f, g)) {
  14. return compose(std::forward<F>(f), std::forward<G>(g));
  15. }
  16.  
  17. int main() {
  18. //identity
  19. assert(5 == identity(5));
  20. assert("asdf"s == identity("asdf"s));
  21. std::string aa = "adsf";
  22. auto new_aa = identity(std::move(aa));
  23. assert(new_aa == "adsf");
  24. assert(aa != "adsf");
  25.  
  26. //composition
  27. auto intTimes10f = [](int a) { return a * 10.f; };
  28. auto floatTimes10s = [](float a) { return std::to_string(a * 10) + " string!"; };
  29. auto intToFloatToStringComposition = compose(floatTimes10s, intTimes10f);
  30. auto compositionByOperator = floatTimes10s * intTimes10f;
  31. std::cout << intToFloatToStringComposition(2);
  32. std::cout << "\nBy operator: " << compositionByOperator(2);
  33.  
  34.  
  35. //composition and identity
  36. auto idInComposition = compositionByOperator * identity;
  37. std::cout << "\nidentity + last composition yields the same value: " << idInComposition(2); //first id is applied, which yields 2 then previous composition works on this value
  38.  
  39. auto reverse = identity * compositionByOperator;
  40. std::cout << "\nnow identity is applied after eval of previous composition: " << reverse(2); //first composition is applied which yields std::string, then id which yields the same std::string
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
200.000000 string!
By operator: 200.000000 string!
identity + last composition yields the same value: 200.000000 string!
now identity is applied after eval of previous composition: 200.000000 string!