如何用C++标准库判断类型是否支持打印或格式化?
C++标准库内置类型检查:可格式化与可打印类型判断
标准库内置的可格式化检查:std::formattable<T>
C20引入的std::formattable<T>是标准库原生的概念,专门用于判断类型T是否支持std::format格式化。使用时需包含<format>头文件,且编译器需支持C20及以上标准,直接在constexpr if中作为条件即可。
标准库内置的可打印检查:std::output_streamable<T>
标准库没有名为std::ostreambale的内置工具,但C++20提供了std::output_streamable<T>概念(来自<concepts>头文件),它的作用就是判断类型是否能通过std::basic_ostream的operator<<完成输出。
修正后的代码实现
以下是符合标准库规范的std::formatter特化代码,使用原生概念完成类型检查:
#include <format> #include <concepts> #include <sstream> #include <string> template<typename DATA_T> struct std::formatter<MyClass<DATA_T>> : std::formatter<std::string> { auto format(const MyClass<DATA_T>& my_class, std::format_context& ctx) const { std::string result = std::format("Name: {}\n", my_class.name()); // 优先检查是否支持std::format格式化 if constexpr (std::formattable<DATA_T>) { result += std::format("Data: {}", my_class.data()); } // 检查是否支持operator<<输出 else if constexpr (std::output_streamable<DATA_T>) { std::ostringstream oss; oss << my_class.data(); result += "Data: "; result += oss.str(); } result += std::format("\nLocation: {}", my_class.location()); return std::format_to(ctx.out(), "{}", result); } };
关键细节说明
std::formattable<T>:仅在C++20及以后可用,依赖<format>头文件,会检查类型是否满足std::format的格式化约束。std::output_streamable<T>:C++20引入,依赖<concepts>头文件,覆盖所有能被std::ostream输出的类型。- 注意
format成员函数必须声明为const,这是标准库formatter对成员函数的要求。
内容的提问来源于stack exchange,提问作者sakcakoca
相关产品推荐
相关产品推荐

