My Project
util.hpp
Go to the documentation of this file.
1#ifndef _UTIL_HPP
2#define _UTIL_HPP
3#include <memory>
4#include <stdexcept>
5#include <string>
6
7template <typename... Args>
8std::string string_format(const std::string &format, Args... args) {
9 int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) +
10 1; // Extra space for '\0'
11 if (size_s <= 0) {
12 throw std::runtime_error("Error during formatting.");
13 }
14 auto size = static_cast<size_t>(size_s);
15 std::unique_ptr<char[]> buf(new char[size]);
16 std::snprintf(buf.get(), size, format.c_str(), args...);
17 return std::string(buf.get(),
18 buf.get() + size - 1); // We don't want the '\0' inside
19}
20#endif // !_UTIL_HPP
std::string string_format(const std::string &format, Args... args)
Definition: util.hpp:8