Search code examples
c++c++23

How to fix C++ 23 std::format error `std::formatter must be specialized for each type being formatted`?


How do I fix the static assertion error

error: static assertion failed: std::formatter must be specialized for each type being formatted

I have a user defined type

enum class HttpMethod {
    GET,
    PUT,
};

and I am trying to use this with std::format, which is used by std::println. (Or std::print.)

std::println("HTTP Method: {}", http_method);

where http_method is an instance of HttpMethod.


Solution

  • An implementation of std::formatter<HttpRequest> is required.

    Here is an example

    template<>
    struct std::formatter<HttpMethod> {
    
        constexpr auto parse(std::format_parse_context& context) {
            return context.begin();
        }
    
        auto format(const HttpMethod& http_method, std::format_context& context) const {
            if(http_method == HttpMethod::GET) {
                return std::format_to(context.out(), "{}", "GET");
            }
            else if(http_method == HttpMethod::PUT) {
                return std::format_to(context.out(), "{}", "PUT");
            }
            else {
                return std::format_to(context.out(), "{}", "UNRECOGNIZED");
            }
        }
    };
    

    Points to note:

    • parse does not parse a string formatted HttpMethod. It parses the format specifier string, the most trivial version of which is {}
    • format contains the actual logic for formatting the HttpMethod as a string