VCCC  2024.05
VisualCamp Common C++ library
formatter.hpp
Go to the documentation of this file.
1 # /*
2 # * Created by YongGyu Lee on 2020/12/08.
3 # */
4 #
5 # ifndef VCCC_LITERAL_FORMATTER_HPP
6 # define VCCC_LITERAL_FORMATTER_HPP
7 #
8 # include <string>
9 # include <vector>
10 # include <cstdio>
11 
12 namespace vccc {
13 
16 
26 class Formatter {
27  public:
28  explicit Formatter(const char *format) : format(format), buffer(30) {}
29 
30  template<typename ...Args>
31  inline std::string operator()(const Args& ...args) {
32  auto size = snprintf(NULL, 0, format, args...);
33  if (buffer.size() < size + 1)
34  buffer.resize(size + 1);
35  snprintf(buffer.data(), size + 1, format, args...);
36  return std::string(buffer.data());
37  }
38 
39  private:
40  const char *format;
41  std::vector<char> buffer;
42 };
43 
44 
59 inline Formatter operator "" _format(const char *format, std::size_t) {
60  return Formatter(format);
61 }
62 
64 
65 } // namespace vccc
66 
67 # endif // VCCC_LITERAL_FORMATTER_HPP
converts c-style format and inputs to std::string
Definition: formatter.hpp:26
Formatter(const char *format)
Definition: formatter.hpp:28
std::string operator()(const Args &...args)
Definition: formatter.hpp:31
Definition: directory.h:12
constexpr auto size(const C &c) -> decltype(c.size())
Definition: size.hpp:16