SHARE
TWEET

Untitled

a guest Mar 26th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <tuple>
  2. #include <utility>
  3. #include <iostream>
  4.  
  5.  
  6. class Aa {
  7.     public:
  8.         Aa(int a1_, int a2_): a1(a1_), a2(a2_) {}
  9.  
  10.         template<std::size_t N>
  11.         decltype(auto) get() const {
  12.             if constexpr (N == 0) return a1;
  13.             else if constexpr (N == 1) return a2;
  14.         }
  15.  
  16.     private:
  17.         int a1;
  18.         int a2;
  19. };
  20.  
  21. class Bb {
  22.     public:
  23.         Bb(Aa a_, int b_): a(a_), b(b_) {}
  24.  
  25.         template<std::size_t N>
  26.         decltype(auto) get() const {
  27.             if constexpr (N == 0) return a;
  28.             else if constexpr (N == 1) return b;
  29.         }
  30.  
  31.     private:
  32.         Aa a;
  33.         int b;
  34.        
  35. };
  36.  
  37. namespace std {
  38.     // Aa
  39.     template<>
  40.     struct tuple_size<Aa> : std::integral_constant<std::size_t, 2> {};
  41.  
  42.     template<std::size_t N>
  43.     struct tuple_element<N, Aa> {
  44.         using type = decltype(std::declval<Aa>().get<N>());
  45.     };
  46.  
  47.     // Bb
  48.     template<>
  49.     struct tuple_size<Bb> : std::integral_constant<std::size_t, 2> {};
  50.  
  51.     template<std::size_t N>
  52.     struct tuple_element<N, Bb> {
  53.         using type = decltype(std::declval<Bb>().get<N>());
  54.     };
  55. }
  56.  
  57. // template <size_t N>
  58. // using size = std::integral_constant<size_t, N>;
  59.  
  60. // template<typename T>
  61. // void encode(T t) {
  62. //     encode_impl<?std::tuple_size<T>?()>(T t, ?std::tuple_size<T>);
  63. // }
  64.  
  65. // template<?>
  66. // encode_impl(T t, ?) {
  67. //    std::cout << "It works";
  68. // }
  69.  
  70. template<typename T>
  71. void encode(T const& t, std::ostream& os)
  72. {
  73.   encode_impl(t, os, std::make_index_sequence<std::tuple_size<T>>{ });
  74. }
  75.  
  76. template<typename T, std::size_t... I>
  77. void encode_impl(T const& t, std::ostream& os, std::index_sequence<I...> const)
  78. {
  79.   constexpr auto last = sizeof...(I) - 1;
  80.   os << "{ ";
  81.   [[maybe_unused]] int const temp[] =
  82.     { ((os << (I != last ? ", " : " ") << t.template get<I>()), 0)... };
  83.   os << "}" << std::endl;
  84. }
  85.  
  86. int main () {
  87.     auto a = Aa(1, 1);
  88.     encode(a, std::cout);
  89.     return 0;
  90. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top