HILA
Loading...
Searching...
No Matches
string_format.h
Go to the documentation of this file.
1/** @file string_format.h */
2
3#ifndef STRING_FORMAT_H_
4#define STRING_FORMAT_H_
5
6#include <string>
7#include <memory>
8
9template <typename... Args>
10std::string string_format(const std::string &format, Args... args) {
11 // wrapper for std::snprintf which sets up buffer of required size
12
13 // determine required buffer size :
14 int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1;
15 if (size_s <= 0) {
16 throw std::runtime_error("Error during formatting.");
17 }
18
19 // allocate buffer :
20 auto size = static_cast<size_t>(size_s);
21 std::unique_ptr<char[]> buf(new char[size]);
22
23 // write formatted string to buffer :
24 std::snprintf(buf.get(), size, format.c_str(), args...);
25
26 return std::string(buf.get(), buf.get() + size - 1);
27}
28
29#endif