diff options
author | gabime <gmelman1@gmail.comx> | 2022-10-31 18:35:24 +0300 |
---|---|---|
committer | gabime <gmelman1@gmail.comx> | 2022-10-31 18:35:24 +0300 |
commit | a7e2bf161e2f038cce2d32131452e8806ed437e1 (patch) | |
tree | 03cc037dba5a9580b13fcb5cd3415619129862d0 | |
parent | 070dd181df89bbdcb26e344c21ede5bc857f555d (diff) |
Update user defined type example
-rw-r--r-- | README.md | 19 | ||||
-rw-r--r-- | example/example.cpp | 22 |
2 files changed, 24 insertions, 17 deletions
@@ -269,21 +269,24 @@ void multi_sink_example2() ---
#### User defined types
```c++
-// user defined types logging by implementing operator<<
-#include "spdlog/fmt/ostr.h" // must be included
-struct my_type
+#ifdef SPDLOG_USE_STD_FORMAT
+namespace std {
+#else
+namespace fmt {
+#endif
+template<>
+struct formatter<my_type> : formatter<std::string>
{
- int i;
- template<typename OStream>
- friend OStream &operator<<(OStream &os, const my_type &c)
+ auto format(my_type my, format_context &ctx) -> decltype(ctx.out())
{
- return os << "[my_type i=" << c.i << "]";
+ return format_to(ctx.out(), "[my_type i={}]", my.i);
}
};
+}
void user_defined_example()
{
- spdlog::get("console")->info("user defined type: {}", my_type{14});
+ spdlog::info("user defined type: {}", my_type(14));
}
```
diff --git a/example/example.cpp b/example/example.cpp index f7b4572b..ccfdcf2f 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -262,22 +262,26 @@ struct my_type : i(i){}; }; -// Using a namespace alias like fmt_lib is not allowed when extending an existing namespace, -// but the correct namespace can still be selected with the SPDLOG_USE_STD_FORMAT macro. -#ifdef SPDLOG_USE_STD_FORMAT -namespace std { -#else -namespace fmt { -#endif +#ifndef SPDLOG_USE_STD_FORMAT // when using fmtlib template<> -struct formatter<my_type> : formatter<std::string> +struct fmt::formatter<my_type> : fmt::formatter<std::string> { auto format(my_type my, format_context &ctx) -> decltype(ctx.out()) { return format_to(ctx.out(), "[my_type i={}]", my.i); } }; -} + +#else // when using std::format +template<> +struct std::formatter<my_type> : std::formatter<std::string> +{ + auto format(my_type my, format_context &ctx) -> decltype(ctx.out()) + { + return format_to(ctx.out(), "[my_type i={}]", my.i); + } +}; +#endif void user_defined_example() { |