r/cpp • u/SPEKTRUMdagreat • Jun 25 '26
std::formatter specialization for smart pointers
Currently something like
std::unique_ptr<int> u_ptr = std::make_unique<int>(42);
std::shared_ptr<int> s_ptr = std::make_shared<int>(42);
std::println("uptr: {}", u_ptr);
std::println("sptr: {}", s_ptr);is ill formed because there is no specialization of std::formatter for smart pointer types.
On the other hand,
std::cout << "uptr: " << u_ptr << '\n';
std::cout << "sptr: " << s_ptr << '\n';do work because ostream defines overloads for smart pointer types.
Please let me know if anyone has thoughts or if there's some reason that these types haven't been specialized that I'm missing.
16
Upvotes
View all comments
Show parent comment
6
u/evaned Jun 26 '26
Genuine question: are you actually allowed to do this? I claim it's not, but I'm not positive.
My understanding of how
std::formatis customized is by providing a specialization ofstd::formatter, a class template.I also understand there to be a standards rule that you cannot specialize a
stdtemplate unless at least one of the template arguments is a program-defined type.I guess I'm not positive how this interacts with
unique_ptrandshared_ptrbeing templates, but at least in OP's mini example there's no user-defined type involved. Perhaps defining a formatter for, say,unique_ptr<a_custom_class>would be permitted, but I am skeptical thatunique_ptr<int>would, and thus that (in practice) a generictemplate<T> formatter<unique_ptr<T>>would be IFNDR once it got instantiated for a built-in type (or one instd).Now, I'm not sure how likely this would be to cause problems in practice, but I understand it to be UB.