fenbf / cppstories-discussions

4 stars 1 forks source link

2022/custom-stdformat-cpp20/ #92

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Custom types and std::format from C++20 - C++ Stories

std::format is a large and powerful addition in C++20 that allows us to format text into strings efficiently. It adds Python-style formatting with safety and ease of use. This article will show you how to implement custom formatters that fit into this new std::format architecture. Quick Introduction to std::format   Here’s the Hello World example:

https://www.cppstories.com/2022/custom-stdformat-cpp20/

2kaud commented 2 years ago

If the result of std::format is to a stream (which is pretty normal), then you could combine stream insertion with std::format for a custom type without getting involved with custom formatters. eg.

#include <iostream>
#include <format>
#include <iterator>

using fmtstrm = std::ostream_iterator<char>;

struct myStrt {
    std::string s;
    int i {};
    double d {};
};

std::ostream& operator<<(std::ostream& os, const myStrt& strt) {
    std::format_to(fmtstrm(os), "{:-^10}:{:0>10}:{:10.3}", strt.s, strt.i, strt.d);
    return os;
}

int main() {
    myStrt st { "hello", 34, 6.78 };

    std::cout << st << '\n';
}

Which displays: --hello---:0000000034: 6.78