mirror of
https://github.com/gabime/spdlog.git
synced 2024-11-15 08:25:43 +08:00
Update user defined type example
This commit is contained in:
parent
070dd181df
commit
a7e2bf161e
19
README.md
19
README.md
@ -269,21 +269,24 @@ void multi_sink_example2()
|
|||||||
---
|
---
|
||||||
#### User defined types
|
#### User defined types
|
||||||
```c++
|
```c++
|
||||||
// user defined types logging by implementing operator<<
|
#ifdef SPDLOG_USE_STD_FORMAT
|
||||||
#include "spdlog/fmt/ostr.h" // must be included
|
namespace std {
|
||||||
struct my_type
|
#else
|
||||||
|
namespace fmt {
|
||||||
|
#endif
|
||||||
|
template<>
|
||||||
|
struct formatter<my_type> : formatter<std::string>
|
||||||
{
|
{
|
||||||
int i;
|
auto format(my_type my, format_context &ctx) -> decltype(ctx.out())
|
||||||
template<typename OStream>
|
|
||||||
friend OStream &operator<<(OStream &os, const my_type &c)
|
|
||||||
{
|
{
|
||||||
return os << "[my_type i=" << c.i << "]";
|
return format_to(ctx.out(), "[my_type i={}]", my.i);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
void user_defined_example()
|
void user_defined_example()
|
||||||
{
|
{
|
||||||
spdlog::get("console")->info("user defined type: {}", my_type{14});
|
spdlog::info("user defined type: {}", my_type(14));
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
@ -262,22 +262,26 @@ struct my_type
|
|||||||
: i(i){};
|
: i(i){};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Using a namespace alias like fmt_lib is not allowed when extending an existing namespace,
|
#ifndef SPDLOG_USE_STD_FORMAT // when using fmtlib
|
||||||
// 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
|
|
||||||
template<>
|
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())
|
auto format(my_type my, format_context &ctx) -> decltype(ctx.out())
|
||||||
{
|
{
|
||||||
return format_to(ctx.out(), "[my_type i={}]", my.i);
|
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()
|
void user_defined_example()
|
||||||
{
|
{
|
||||||
|
Loading…
Reference in New Issue
Block a user