Skip to content

Instantly share code, notes, and snippets.

@Gnomorian
Created December 20, 2021 11:17
Show Gist options
  • Save Gnomorian/6ec50c63718a523fb41ffa0e357f8d22 to your computer and use it in GitHub Desktop.
Save Gnomorian/6ec50c63718a523fb41ffa0e357f8d22 to your computer and use it in GitHub Desktop.
an example of how to write a custom std::formatter
#include <iostream>
#include <format>
#include <iterator>
class Thing
{
public:
std::string s{ "some text" };
};
template<class CharT>
struct std::formatter<Thing, CharT> : std::formatter<std::string, CharT>
{
/*
Example of a Custom std::formatter for an example class called Thing.
Writes "Thing{" + Thing::s + "}".
*/
// Define format() by calling the base class implementation with the wrapped value
template<class FormatContext>
auto format(Thing t, FormatContext& fc)
{
std::formatter<std::string, CharT>::format("Thing{", fc);
std::formatter<decltype(Thing::s), CharT>::format(t.s, fc);
*fc.out()++ = '}';
return fc.out();
}
};
int wmain(int argc, wchar_t* args[])
{
Thing t;
std::cout << std::format("{}", t);
// writes: Thing{some text}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment