fork(2) download
  1. #include <tuple>
  2.  
  3. struct Cache;
  4.  
  5. template<int, typename> struct cache_getter;
  6. template<int, typename...> struct tuple_walker;
  7.  
  8. template<int I, typename... Ts> struct cache_getter<I, std::tuple<Ts...> > {
  9. static std::tuple<Ts...> get(Cache & c);
  10. };
  11.  
  12. struct Cache {
  13. protected:
  14. template<int, typename...> friend struct tuple_walker;
  15. private:
  16. /* here T is a type from within a std::tuple<...> */
  17. template<int I, typename T> std::tuple<T> get_ex() {
  18. return std::tuple<T>();
  19. }
  20. public:
  21. /* here T is actually a std::tuple<...> */
  22. template<typename T> T get() {
  23. return cache_getter<0, T>::get(*this);
  24. }
  25. };
  26.  
  27. template<typename...> struct my_tuple_cat;
  28. template<typename H, typename... T> struct my_tuple_cat<H, T...> {
  29. static auto cat(H h, T... t) -> decltype(std::tuple_cat(h, my_tuple_cat<T...>::cat(t...)))
  30. { return std::tuple_cat(h, my_tuple_cat<T...>::cat(t...)); }
  31. };
  32. template<typename T> struct my_tuple_cat<T> {
  33. static T cat(T t) { return t; }
  34. };
  35.  
  36.  
  37. template<int I, typename H, typename... T> struct tuple_walker<I, H, T...> {
  38. static std::tuple<H, T...> get(Cache & c) {
  39. return my_tuple_cat<std::tuple<H>, std::tuple<T...>>::cat(c.get_ex<I, H>(), tuple_walker<I + 1, T...>::get(c));
  40. }
  41. };
  42. template<int I, typename H> struct tuple_walker<I, H> {
  43. static std::tuple<H> get(Cache & c) {
  44. return c.get_ex<I, H>();
  45. }
  46. };
  47.  
  48. template<int I, typename... Ts> std::tuple<Ts...> cache_getter<I, std::tuple<Ts...> >::get(Cache & c) {
  49. return tuple_walker<I, Ts...>::get(c);
  50. }
  51.  
  52. int main(int argc, char ** argv) {
  53. Cache cache;
  54. typedef std::tuple<int, double, bool> InstrumentTuple;
  55. InstrumentTuple tuple = cache.get<InstrumentTuple>();
  56. return 0;
  57. }
Success #stdin #stdout 0s 2892KB
stdin
Standard input is empty
stdout
Standard output is empty