Format your own type (Part 1) -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGI recently published two posts about how C++26 improves std::format and the related facilities. (If you missed them, here are Part 1 and Part 2). Now it’s time to explore how you can format your own types using std::format.

Format your own type (Part 1)

by Sandor Dargo

From the article:

std::format was introduced in C++20 and is based on Victor Zverovich’s <fmt> library, which in turn was inspired by Python’s string formatting capabilities.

Let’s skip the fancy formatting options and simply see how to interpolate values using std::format.

#include <format>
#include <iostream>
#include <string>

int main() {
    std::string language{"C++"};
    int version{20};
    std::cout << std::format("{}{} is fun", language, version) << '\n';
}

/*
C++20 is fun
*/

That was easy.

Now imagine you want to print your own type. That won’t work by default.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.