fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <string>
  4. #include <cassert>
  5.  
  6. // Call f with one argument
  7. template <class Fn, class Arg>
  8. auto call(const Fn &f, const Arg & arg) -> decltype(f(arg)) {
  9. return f(arg);
  10. }
  11.  
  12. // Helper functor for the function below
  13. template<class Fn1, class Fn2>
  14. class CompFn {
  15. Fn1 a;
  16. Fn2 b;
  17.  
  18. public:
  19. CompFn(const Fn1 &f1, const Fn2 &f2) : a(f1), b(f2) {}
  20.  
  21. template<class Arg> inline
  22. auto operator()(const Arg & arg) const -> decltype(call(b, call(a, arg))) {
  23. return call(b, call(a, arg));
  24. }
  25. };
  26.  
  27. /** Composition of f1 and f2 (f2 after f1). */
  28. template<class Fn1, class Fn2>
  29. CompFn<Fn1,Fn2> comp(const Fn1 &f1, const Fn2 &f2) {
  30. return CompFn<Fn1,Fn2>(f1, f2);
  31. }
  32.  
  33.  
  34.  
  35. int main() {
  36. // Example: Take the length of the string and compare it against zero.
  37. std::function<int(std::string)> stringLength = [](std::string s) { return s.size(); };
  38. std::function<bool(int)> greaterZero = [](int x) { return x > 0; };
  39. auto stringNotEmpty = comp(stringLength, greaterZero);
  40.  
  41. std::string testInput1 = "foo";
  42. std::string testInput2 = "";
  43.  
  44. assert(stringNotEmpty(testInput1) == true);
  45. assert(stringNotEmpty(testInput2) == false);
  46. }
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
Standard output is empty