sapphirec
The Sapphire documentation
FormatString.hpp
Go to the documentation of this file.
1 // Taken from https://github.com/InversePalindrome/Blog/blob/master/FormatString/FormatString.hpp
2 
3 /*
4 Copyright (c) 2019 Inverse Palindrome
5 Blog - FormatString.hpp
6 https://inversepalindrome.com/
7 */
8 
9 #pragma once
10 
11 #include <memory>
12 #include <string>
13 #include <cstdio>
14 
15 
16 template<typename T>
17 auto convert(T&& t)
18 {
19  if constexpr (std::is_same<std::remove_cv_t<std::remove_reference_t<T>>, std::string>::value)
20  {
21  return std::forward<T>(t).c_str();
22  }
23  else
24  {
25  return std::forward<T>(t);
26  }
27 }
28 
29 template<typename... Args>
30 std::string format_string_internal(const std::string& format, Args&& ... args)
31 {
32  const auto size = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...) + 1;
33  const auto buffer = std::make_unique<char[]>(size);
34 
35  std::snprintf(buffer.get(), size, format.c_str(), std::forward<Args>(args)...);
36 
37  return std::string(buffer.get(), buffer.get() + size - 1);
38 }
39 
40 template<typename... Args>
41 std::string format_string(const std::string& format, Args&& ... args)
42 {
43  return format_string_internal(format, convert(std::forward<Args>(args))...);
44 }
std::string format_string_internal(const std::string &format, Args &&... args)
Definition: FormatString.hpp:30
auto convert(T &&t)
Definition: FormatString.hpp:17
std::string format_string(const std::string &format, Args &&... args)
Definition: FormatString.hpp:41