fork(1) download
  1. #include <typeinfo>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. template <typename typed, int i> struct enumerate
  7. {
  8. static auto get(typed x) -> decltype(x.template get<i>()) { return x.template get<i>(); };
  9. const static bool has_next = !is_same<decltype(typed().template get<i+1>()), void>::value;
  10. typedef enumerate<typed, has_next?i+1:0> next;
  11. };
  12.  
  13. struct smth
  14. {
  15. template <int i> struct key_t {};
  16.  
  17. template <int i> void get(key_t<i>) {}
  18.  
  19. int x; int get(key_t<1>) { return this->x; }
  20. double y; double get(key_t<2>) { return this->y; }
  21.  
  22. template <int i> auto get() -> decltype(this->get(key_t<i>())) { return this->get(key_t<i>()); }
  23. };
  24.  
  25. int main()
  26. {
  27. smth s = {1, 2.5};
  28.  
  29. cout.setf(ios::boolalpha);
  30.  
  31. cout << s.x << ' ' << s.y << endl;
  32. cout << s.get<1>() << ' ' << s.get<2>() << endl;
  33. cout << endl;
  34. cout << enumerate<smth, 1>::get(s) << ' ' << enumerate<smth, 1>::has_next << endl;
  35. cout << enumerate<smth, 1>::next::get(s) << ' ' << enumerate<smth, 1>::next::has_next << endl;
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
1 2.5
1 2.5

1 true
2.5 false