c++c++23stdformat

C++23 std::print


Based on the standard C++23 is it possible to use std::print for custom objects? Something like this

#include <iostream>
#include <string>
#include <format>  

struct Person {
    std::string name;
    int age;
};


template <>
struct std::formatter<Person> : std::formatter<std::string> {
   
    auto format(const Person& p, std::format_context& ctx) {
        return std::format_to(ctx.out(), "Name: {}, Age: {}", p.name, p.age);
    }
};

int main() {
    Person p1{"Alice", 32};

    std::cout << std::format("{}", p1) << std::endl;  

    std::print("{}\n", p1); 

    return 0;
}

I tried this but fail to compile

/opt/compiler-explorer/clang-trunk-20250119/bin/../include/c++/v1/__format/format_arg_store.h:168:17: error: static assertion failed due to requirement '__arg != __arg_t::__none': the supplied type is not formattable 168 | static_assert(__arg != __arg_t::__none, "the supplied type is not formattable"); | ^~~~~~~~~~~~~~~~~~~~~~~~ /opt/compiler-explorer/clang-trunk-20250119/bin/../include/c++/v1/__format/format_arg_store.h:214:54: note: in instantiation of function template specialization 'std::__format::__create_format_arg<std::format_context, Person>' requested here 214 | basic_format_arg<_Context> __arg = __format::__create_format_arg<_Context>(__args); |

Example


Solution

  • Works for me if you add #include <print> for the std::print function. You also need to mark the format member with a const.

    auto format(const Person& p, std::format_context& ctx) const {
                                                      ------^
    

    The last part comes from the formattable concept, which requires a const formatter& to be useable when creating the output.