Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't particularly mind the ^^ and [::] sigils, but the 'template for (constexpr auto ...)' is a bit ugly and hard to explain to a beginner.

But interestingly the code can be improved. The issue is that meta::info[1] is a pure compile time object so in the original code we need to statically unroll the loop of the vector that contains it so that we can splice it in in the loop body. But if we convert it to our own objects, then we can use a plain for loop.

  template<class T>
  constexpr static inline auto reflect_type = ^^T; // not really necessary

  template <typename T>
    requires std::is_enum_v<T>
  constexpr std::string_view to_enum_string(T val)
  {
     struct my_string_view { const char * ptr; size_t sz = strlen(ptr); }; 
     static constexpr auto meta = std::define_static_array(
          std::meta::enumerators_of(reflect_type<T>)
        | std::ranges::views::transform(
        [](auto e) { 
          return std::pair{my_string_view{define_static_string(std::meta::identifier_of(e))}, extract<T>(e)}; 
        }));;

     for (auto [name, value] : meta)        
     {
        if (val == value) { return name; }
     }
     return "<unknown>";
  }
This actually generate less code bloat as, if the array is large it will use a plain loop instead of always unrolling. Also the meta array can now be used for as lookup table for dense enums, while I don't think it is doable with the original version. Supposedly GCC should be able to convert a if chain into a switch statement, but it doesn't seem to trigger here [edit: scratch that: GCC does the switch conversion for the original version].

define_static{_array,_string} still feel as unnecessary magic, but hopefully they are only transient and we will be able to use std::vectors directly. Also somehow GCC doesn't let me use std::string_view and I had to introduce an helper string type.

edit: I literally learned everything I know about static reflection in the last 24 hours. It is complicated, but not that complicated.

[1] Not sure why, I suspect they want to avoid being constrained by ABI.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: