示例代码
#include
#include
#include
struct Vector4D
{
int x, y, z, s;
};
namespace std {
template <>
class formatter<Vector4D> {
public:
explicit formatter() noexcept
: _fmt(OutputFormat::XYZS)
{ }
typename std::basic_format_parse_context<char>::iterator
parse(std::basic_format_parse_context<char>& pc) {
if (pc.begin() == pc.end() || *pc.begin() == '}') {
_fmt = OutputFormat::XYZS;
return pc.end();
}
switch (*pc.begin()) {
case 'X':
_fmt = OutputFormat::X;
break;
case 'Y':
_fmt = OutputFormat::Y;
break;
case 'Z':
_fmt = OutputFormat::Z;
break;
case 'S':
_fmt = OutputFormat::S;
default:
throw std::format_error("Invalid format specification");
}
return pc.begin() + 1;
}
template <typename OutputIt>
std::basic_format_context<OutputIt, char>::iterator
format(const Vector4D& value, std::basic_format_context<OutputIt, char>& fc) const noexcept {
std::string valueString;
switch (_fmt) {
case OutputFormat::XYZS: {
valueString = std::format("X={}, Y={}, Z={}, S={}",
value.x, value.y, value.z, value.s);
break;
}
case OutputFormat::X:
valueString = std::format("X={}", value.x);
break;
case OutputFormat::Y:
valueString = std::format("Y={}", value.y);
break;
case OutputFormat::Z:
valueString = std::format("Z={}", value.z);
break;
case OutputFormat::S:
valueString = std::format("S={}", value.s);
break;
}
auto output = fc.out();
for (auto ch : valueString) {
*output++ = ch;
}
return output;
}
private:
enum class OutputFormat {
X,
Y,
Z,
S,
XYZS
};
OutputFormat _fmt;
};
}
int main()
{
Vector4D v = { 1, 2, 3, 4 };
std::cout << std::format("{}", v) << std::endl;
return 0;
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99