fork(1) download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. using namespace std;
  5.  
  6. template<typename a, class derived>
  7. class functor
  8. {
  9. public:
  10. virtual ~functor()
  11. {}
  12. template<typename b>
  13. derived map(const std::function<b(a)> &f)
  14. {
  15. // Here you take advantage of the CRTP
  16. return static_cast<derived*>(this)->map(f);
  17. }
  18. };
  19.  
  20. template<typename l, typename r>
  21. class either : public functor<r, either<l, r>>
  22. {
  23. public:
  24. template<typename b>
  25. either<l, b> map(const std::function<b(r)> &f)
  26. {
  27. cout << "In derived" << endl;
  28. return either<l, b>();
  29. }
  30. };
  31.  
  32. int main()
  33. {
  34. // pointer to base class points to a derived object
  35. functor<int, either<int, int>> *ff = new either<int, int>();
  36. // map function will call the method of the derived class
  37. ff->map<int>([](int k){ return 1; });
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
In derived