fork(2) download
  1. #include <iostream>
  2. #include <functional>
  3. #include <list>
  4. using namespace std;
  5.  
  6.  
  7. template <typename R, typename... Arg>
  8. function<R (Arg...)> decor(
  9. initializer_list<
  10. function<function<R (Arg...)> (function<R (Arg...)>)>
  11. > transformers,
  12. function<R (Arg...)>&& func)
  13. {
  14. list<function<function<R (Arg...)> (function<R (Arg...)>)>> tfs;
  15. tfs.assign(transformers);
  16. tfs.reverse();
  17.  
  18. function<R (Arg...)> fn = func;
  19. for (auto tf : tfs) {
  20. fn = tf(fn);
  21. }
  22. return fn;
  23. }
  24.  
  25. template <typename F>
  26. F add42(F fn) {
  27. return [=] (int x) -> int {
  28. return fn(x) + 42;
  29. };
  30. }
  31.  
  32. template <typename F>
  33. F div2(F fn) {
  34. return [=] (int x) -> int {
  35. return fn(x) / 2;
  36. };
  37. }
  38.  
  39. auto func = decor({add42, div2}, [=] (int x) -> int {
  40. return x * 2;
  41. });
  42.  
  43. int main() {
  44. cout << "f(1) = " << func(1) << endl;
  45. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:41:2: error: no matching function for call to ‘decor(<brace-enclosed initializer list>, <lambda(int)>)’
prog.cpp:41:2: note: candidate is:
prog.cpp:8:26: note: template<class R, class ... Arg> std::function<_Res(_ArgTypes ...)> decor(std::initializer_list<std::function<std::function<_Res(_ArgTypes ...)>(std::function<_Res(_ArgTypes ...)>)> >, std::function<_Res(_ArgTypes ...)>&&)
prog.cpp:8:26: note:   template argument deduction/substitution failed:
prog.cpp:41:2: note:   ‘<lambda(int)>’ is not derived from ‘std::function<_Res(_ArgTypes ...)>’
prog.cpp:41:2: error: unable to deduce ‘auto’ from ‘<expression error>’
stdout
Standard output is empty