std::format

std::format基本

printf()と同じ感覚で、書式と変数を指定する。置換フィールド({と}で囲まれた部分)に置換フィールド書式を指定するが、デフォルトの書式で良ければ省略できる。

#include <format>
#include <iostream>

int main(){
    auto i{5};
    auto str{"abc"};
    std::cout << std::format("i={}, str={}\n'", i, str);    // =>  "i=5, str=abc"
}

置換フィールドに書式を指定する例

#include <format>
#include <iostream>

int main(){
    auto i{15};
    // 6桁の16進表現,先行0埋め
    std::cout << std::format("i={:#06x}\n", i); // => "i=0x000f"
}

独自のフォーマットを定義する

#include <format>
#include <iostream>

struct coord {
    float x_{0.0};
    float y_{0.0};
    float z_{0.0};
};

// coord用のカスタムフォーマット定義
template <>
struct std::formatter<coord> {
    constexpr auto parse(std::format_parse_context& ctx) {
        return ctx.begin();
    }

    auto format(const coord& obj, std::format_context& ctx) {
        return std::format_to(ctx.out(), "x={},y={},z={}", obj.x_, obj.y_, obj.z_);
    }
};

int main(){
    coord c{10.0, 20.5, 30.0};

    std::cout << std::format("{}", c); // => "x=10,y=20.5,z=30"
}