I have code that allows you to make a std::string format()
function on any class and allow that class to be used in calls to std::format()
. To do this I say that it requires
a method that returns a std::string
– can I change this somehow to say format can return “any type that’s std::format()
able”?
Example code:
#include <format>
#include <iostream>
template<typename T>
requires requires (T v) {
{ v.format() } -> std::convertible_to<std::string>;
}
struct std::formatter<T> : formatter<std::string>
{
auto format(T t, format_context& ctx) const
{
return formatter<std::string>::format(t.format(), ctx);
}
};
struct MyStruct
{
std::string format() const { return "I'm a struct"; }
};
int main()
{
MyStruct my_struct;
std::cout << std::format("outside: {}", my_struct) << std::endl;
}