温馨提示×

c++的std::format是否支持自定义类型格式化

c++
小樊
98
2024-08-11 05:17:39
栏目: 编程语言

在C++20中引入了std::format库,它可以用来进行字符串格式化操作。std::format库支持自定义类型格式化,可以通过重载operator<<或者定义一个名为formatter的内部类来实现自定义类型的格式化。

下面是一个示例,演示如何使用std::format自定义类型格式化:

#include <format>
#include <string>

// 自定义类型
struct Point {
    int x;
    int y;
};

// 定义formatter内部类来格式化自定义类型Point
template <>
struct std::formatter<Point> {
    // 格式化函数
    template <typename ParseContext>
    auto format(const Point& p, ParseContext& ctx) {
        return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
    }
};

int main() {
    Point p{2, 3};
    std::string formatted = std::format("Point coordinates: {}", p);
    // 输出: Point coordinates: (2, 3)
    std::cout << formatted << std::endl;

    return 0;
}

在上面的示例中,我们定义了一个名为Point的自定义类型,并且定义了一个名为formatter的内部类来格式化Point类型。在主函数中,我们使用std::format来格式化Point类型的对象,并输出结果。

通过这种方式,你可以使用std::format来格式化自定义类型,从而更灵活地进行字符串格式化操作。

0