Post

C++23 Finally Made Logging Good

Writing Easy Debug Messages

C++23 Finally Made Logging Good

Introduction

Today, we’ll be looking at the new <print> library introduced in C++23 to help you write easier debug messages.

Functions

The functions we’ll be exploring are std::print, std::println, and std::format (which was introduced in C++20).

Printing Example

Use std::print or std::println with the {} formatter to easily print anything including STL containers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <map>
#include <print>
#include <set>
#include <string>
#include <vector>

int main() {
    // Using std::print with a format string
    std::print("Hello, {}!\n", "World");

    std::vector<int>           v = { 1, 2, 3, 4, 5 };
    std::set<std::string>      s = { "apple", "banana", "cherry" };
    std::map<int, std::string> m = {
        { 1,	 "one" },
            { 2,   "two" },
        { 3, "three" }
    };
    // Using std::println to print various data structures
    std::println("Vector: {}", v);
    std::println("Set: {}", s);
    std::println("Map: {}", m);

    return 0;
}

Output:

1
2
3
4
Hello, World!
Vector: [1, 2, 3, 4, 5]
Set: {"apple", "banana", "cherry"}
Map: {1: "one", 2: "two", 3: "three"}

Formatting Example

Use std::format to create a formatted string.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <format>
#include <print>

struct Point {
    int x, y;
};

int main() {
    Point p{ 3, 4 };
    // Using std::println with a formatted string
    std::string s = std::format("({}, {})", p.x, p.y);
    std::println("Point: {}", s);
}

Output:

1
Point: (3, 4)

Alternatively, create a custom formatter for your structs/classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <format>
#include <print>

struct Point {
    int x, y;
};

template <>
struct std::formatter<Point> : std::formatter<std::string> {
    auto format(const Point &p, std::format_context &ctx) const {
        return std::formatter<std::string>::format(
            std::format("({}, {})", p.x, p.y), ctx);
    }
};

int main() {
    Point p{ 3, 4 };
    // Using std::println with a custom formatter
    std::println("Point: {}", p);
}

Output:

1
Point: (3, 4)

The function format is required to be const.

Conclusion

The <print> library modernizes C++ and is a handy addition for new, personal projects.

Happy Coding!


System Info

  • macOS: Apple M4
  • Compiler: Clang 20.1.8 (Homebrew LLVM)
  • Standard: C++26
This post is licensed under CC BY 4.0 by the author.