通过回退到带有 fmt 库的指针来格式化类型
Formatting type by fallback to pointer with fmt library
我正在尝试使用
fmt::format("Expected : '{}' vs. '{}'", getDataOrPointer(rA), getDataOrPointer(rB));
其中 getDataOrPointer
应该 return 一个 void
指针(它总是可以被格式化)或者存在格式化程序时的默认值:
//! Return the type if a `fmt::formatter` exists.
template<typename T,
typename std::enable_if_t<hasFormatter<std::decay<T>, char>>* = 0>
decltype(auto) getDataOrPointer(const T& rData)
{
return rData;
}
//! Return a void-Pointer if no `fmt::formatter` exists.
template<typename T,
typename std::enable_if_t<!hasFormatter<std::decay<T>, char>>* = 0>
const void* getDataOrPointer(const T& rData)
{
return static_cast<const void*>(&rData);
}
我不知道如何写:hasFormatter<T,char>
来检查它是否可以被 fmt
库格式化?。我只希望在本地使用此回退。
您可以使用 fmt::has_formatter
,引用 https://github.com/fmtlib/fmt/issues/1369:
has_formatter<T, Context>
tells you that type T
has a formatter
specialization for Context
(context basically specifies character and output iterator types) and it can be used with SFINAE. Example: https://godbolt.org/z/pCD14x. The main caveat is that types with implicit conversion can be formattable but not have a formatter
specialization.
我正在尝试使用
fmt::format("Expected : '{}' vs. '{}'", getDataOrPointer(rA), getDataOrPointer(rB));
其中 getDataOrPointer
应该 return 一个 void
指针(它总是可以被格式化)或者存在格式化程序时的默认值:
//! Return the type if a `fmt::formatter` exists.
template<typename T,
typename std::enable_if_t<hasFormatter<std::decay<T>, char>>* = 0>
decltype(auto) getDataOrPointer(const T& rData)
{
return rData;
}
//! Return a void-Pointer if no `fmt::formatter` exists.
template<typename T,
typename std::enable_if_t<!hasFormatter<std::decay<T>, char>>* = 0>
const void* getDataOrPointer(const T& rData)
{
return static_cast<const void*>(&rData);
}
我不知道如何写:hasFormatter<T,char>
来检查它是否可以被 fmt
库格式化?。我只希望在本地使用此回退。
您可以使用 fmt::has_formatter
,引用 https://github.com/fmtlib/fmt/issues/1369:
has_formatter<T, Context>
tells you that typeT
has aformatter
specialization forContext
(context basically specifies character and output iterator types) and it can be used with SFINAE. Example: https://godbolt.org/z/pCD14x. The main caveat is that types with implicit conversion can be formattable but not have aformatter
specialization.