fork download
  1. template<class T, class D>
  2. class switch_with_default;
  3. template<class T>
  4. class switch_impl {
  5. public:
  6. switch_impl(const T& t_) : t(&t_), matched(false) {}
  7. template<class U, class F>
  8. switch_impl& case_(const U& u, const F& f) {if(!matched&&*t==u){matched=true;f();}return *this;}
  9. template<class D>
  10. switch_with_default<T,D> default_(const D& d);
  11. protected:
  12. template<class U, class D>
  13. friend class switch_with_default;
  14. const T* t;
  15. bool matched;
  16. };
  17. template<class T, class D>
  18. class switch_with_default {
  19. public:
  20. template<class U, class F>
  21. switch_with_default& case_(const U& u, const F& f) {impl->case_(u,f); return *this;}
  22. ~switch_with_default() {if (!impl->matched) (*d)();}
  23. protected:
  24. friend switch_impl<T>;
  25. switch_with_default(switch_impl<T>& impl_, const D& d_) :impl(&impl_), d(&d_) {}
  26. switch_impl<T>* impl;
  27. const D* d;
  28. };
  29. template<class T> template<class D>
  30. switch_with_default<T,D> switch_impl<T>::default_(const D& d) {return switch_with_default<T,D>(*this, d);}
  31. template<class T>
  32. switch_impl<T> switch_(const T& t) {return switch_impl<T>(t);}
  33.  
  34.  
  35.  
  36.  
  37.  
  38. #include <iostream>
  39. int main() {
  40. std::string input = "MooingDuck";
  41.  
  42. switch_(input)
  43. .case_("First", [](){std::cout << "FAILURE1\n";})
  44. .case_("MooingDuck", [](){std::cout << "SUCCESS\n";})
  45. .case_("Third", [](){std::cout << "FAILURE2\n";});
  46.  
  47. switch_(input)
  48. .case_("First", [](){std::cout << "FAILURE1\n";})
  49. .default_([](){std::cout << "SUCCESS\n";})
  50. .case_("Third", [](){std::cout << "FAILURE2\n";});
  51. }
  52.  
  53.  
  54.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
SUCCESS
SUCCESS