Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C++

std::format_to: formatowanie do iteratora wyjściowego

std::format_to zapisuje sformatowane znaki przez iterator wyjściowy i zwraca iterator za ostatnim zapisem.

Wersja: C++23

Składnia

template<class Out, class... Args>
Out std::format_to(Out out, std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, std::wformat_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, const std::locale& loc,
    std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, const std::locale& loc,
    std::wformat_string<Args...> fmt, Args&&... args);

std::format_to(out, fmt, args...) z <format> formatuje argumenty jak std::format, lecz nie tworzy wynikowego napisu: kolejne znaki przypisuje przez iterator out. Zwracany iterator wskazuje miejsce bezpośrednio po ostatnim zapisanym znaku. Dostępne są warianty dla char i wchar_t oraz przeciążenia przyjmujące std::locale.

Przykład zapisuje "2 + 3 = 5" do początku tablicy znaków, a z różnicy między zwróconym iteratorem i początkiem wylicza 9 zapisanych znaków, dlatego drukuje 2 + 3 = 5|9. Funkcja nie dopisuje bajtu zerowego; widok otrzymuje więc jawną długość. Do kontenera o zmiennym rozmiarze zwykle przekazuje się std::back_inserter.

Iterator docelowy musi przyjmować znaki właściwego typu i pozostać zapisywalny przez cały wynik. Zwykły iterator do zbyt małego bufora przestaje spełniać wymagania iteratora wyjściowego, a dalszy zapis ma zachowanie niezdefiniowane; format_to nie zna pojemności. Literał format_string jest sprawdzany względem argumentów, błędy formatowania mogą zgłosić std::format_error, alokacja std::bad_alloc, a wyjątki formattera lub iteratora są propagowane. Gdy potrzebny jest limit zapisu, służy std::format_to_n.

Przykłady

#include <array>
#include <format>
#include <iostream>
#include <string_view>

int main() {
    std::array<char, 32> buffer{};
    const auto end = std::format_to(buffer.begin(), "{} + {} = {}", 2, 3, 5);
    const std::string_view result(buffer.data(), end - buffer.begin());
    std::cout << result << '|' << result.size() << '\n';
}

Wynik

2 + 3 = 5|9

std::format_to → 2 + 3 = 5|9

Źródła