Neargye / magic_enum

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code
MIT License
4.88k stars 434 forks source link

std::format() and std::print() support? #334

Closed ScottBailey closed 3 months ago

ScottBailey commented 8 months ago

I'm not sure if this is misuse by me or a defect.

Using clang-18 and libc++-18: I cannot get the following to work...

#include <magic_enum.hpp>                                                                                                                        
#include <magic_enum_format.hpp>                                                                                                                 

enum class my_enum {a, b, c}; 

int main(int,char**)                                                                                                                             
{                                                                                                                                                
  std::println("Enabled? {}", magic_enum::customize::enum_format_enabled<my_enum>());                                                            
  const std::string a = std::format("a? {}",my_enum::a);                                                                                         
  std::println("ab: {} {}", a, my_enum::b);                                                                                                      
  return 0;                                                                                                                                      
}                                                                                                                                                

...without force defining _cpp_lib_format...

#if !defined(__cpp_lib_format)                                                                                                                   
# define __cpp_lib_format 1                                                                                                                      
#endif 

...and adding a template line to this code to make it:

struct std::formatter<E, std::enable_if_t<std::is_enum_v<std::decay_t<E>> && magic_enum::customize::enum_format_enabled<E>(), char>> : std::formatter<std::string_view, char> {
  template<typename format_context>         // ADDED
  auto format(E e, format_context& ctx) const {

Any insight would be appreciated. Thank you!

Neargye commented 3 months ago

Quite strange, if compiler support <format> then __cpp_lib_format if defined, see https://en.cppreference.com/w/cpp/utility/feature_test

Neargye commented 3 months ago

Looks like fixed in https://github.com/Neargye/magic_enum/pull/365