pflib v3.9.0-rc3-11-g2537d8f
Pretty Fine HGCROC Interaction Library
Loading...
Searching...
No Matches
string_format.h
1#pragma once
2
3#include <memory>
4#include <string>
5
6#include "pflib/Exception.h"
7
8namespace pflib::utility {
9
30template <typename... Args>
31std::string string_format(const std::string& format, Args... args) {
32 // length of string without the closing null byte \0
33 int size_s = std::snprintf(nullptr, 0, format.c_str(), args...);
34 if (size_s < 0) {
35 PFEXCEPTION_RAISE("string_format",
36 "error during formating of string " + format);
37 }
38 // need one larger for the closing null byte
39 auto size = static_cast<std::size_t>(size_s + 1);
40 std::unique_ptr<char[]> buffer(new char[size]);
41 // do format again, but this time we know the size and that it works!
42 std::snprintf(buffer.get(), size, format.c_str(), args...);
43 // remove trailing null byte when copying into std::string
44 return std::string(buffer.get(), buffer.get() + size - 1);
45}
46
47} // namespace pflib::utility
T c_str(T... args)
T snprintf(T... args)
T get(T... args)
Dumping ground for various functions that are used in many places.
Definition crc.cxx:9
std::string string_format(const std::string &format, Args... args)
Backport of C++20 std::format-like function.
Definition string_format.h:31