template <char...> type operator "" _op();
auto x = 10001000100011001001001010001000_b;
template <typename CharT, CharT ...String> type operator "" _op();
template<char ... Chars> struct str { static constexpr const char value[sizeof...(Chars)+1] = {Chars...,'\0'}; static constexpr int size = sizeof...(Chars); }; template<char ... Chars> constexpr const char str<Chars...>::value[sizeof...(Chars)+1];
template<typename CharT, CharT ...String> constexpr str<String...> operator"" _s() { return str<String...>(); }
template<class Type, class Key> struct field { using key = Key; using type = Type; type value; }; template<class,class,int N=0> struct field_by_type; template<class Key, class Type, class ... Tail, int N> struct field_by_type<Key, std::tuple<field<Type,Key>,Tail...>, N> { static constexpr int value = N; }; template<class Key, class Head, class ... Tail, int N> struct field_by_type<Key, std::tuple<Head,Tail...>, N> : field_by_type<Key,std::tuple<Tail...>,N+1> {}; template<class ... Fields> struct record { using tuple_type = std::tuple<Fields...>; template<class Key> typename std::tuple_element<field_by_type<Key,tuple_type>::value,tuple_type>::type::type& operator[](Key) { return std::get<field_by_type<Key,tuple_type>::value>(data).value; } template<class Key> const typename std::tuple_element<field_by_type<Key,tuple_type>::value,tuple_type>::type::type& operator[](Key) const { return std::get<field_by_type<Key,tuple_type>::value>(data).value; } tuple_type data; };
template<class Type, class Key> std::ostream& operator<< (std::ostream& os, const field<Type,Key> f){ os << Key::value << " = " << f.value << "\n"; return os; } template<int I, typename... Ts> struct print_tuple { std::ostream& operator() (std::ostream& os, const std::tuple<Ts...>& t) { os << std::get<sizeof...(Ts)-I>(t); return print_tuple<I - 1, Ts...>{}(os,t); } }; template<typename... Ts> struct print_tuple<0, Ts...> { std::ostream& operator() (std::ostream& os, const std::tuple<Ts...>& t) { return os; } }; template<class ... Fields> std::ostream& operator<< (std::ostream& os, const record<Fields...>& r) { os << "{\n"; print_tuple<sizeof...(Fields),Fields...>{}(os,r.data); os << "}"; return os; }
using Person = record< field<int, decltype("id"_s)>, field<std::string, decltype("first_name"_s)>, field<std::string, decltype("last_name"_s)> >; int main(){ Person p; p["id"_s] = 10; p["first_name"_s] = "John"; p["last_name"_s] = "Smith"; std::cout << p << "\n"; }
class Person : public record< field<int, decltype("id"_s)>, field<std::string, decltype("first_name"_s)>, field<std::string, decltype("last_name"_s)> > { public: void set_name(const std::string& f,const std::string& l) { (*this)["first_name"_s] = f; (*this)["last_name"_s] = l; }; }; int main(){ Person p; p["id"_s] = 10; p.set_name("John","Smith"); std::cout << p << "\n"; }
Source: https://habr.com/ru/post/243581/
All Articles