format.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ///|/ Copyright (c) Prusa Research 2020 Vojtěch Bubník @bubnikv
  2. ///|/
  3. ///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
  4. ///|/
  5. #ifndef slic3r_format_hpp_
  6. #define slic3r_format_hpp_
  7. // Functional wrapper around boost::format.
  8. // One day we may replace this wrapper with C++20 format
  9. // https://en.cppreference.com/w/cpp/utility/format/format
  10. // though C++20 format uses a different template pattern for position independent parameters.
  11. //
  12. // Boost::format works around the missing variadic templates by an ugly % chaining operator. The usage of boost::format looks like this:
  13. // (boost::format("template") % arg1 %arg2).str()
  14. // This wrapper allows for a nicer syntax:
  15. // Slic3r::format("template", arg1, arg2)
  16. // One can also override Slic3r::internal::format::cook() function to convert a Slic3r::format() argument to something that
  17. // boost::format may convert to string, see slic3r/GUI/I18N.hpp for a "cook" function to convert wxString to UTF8.
  18. #include <boost/format.hpp>
  19. namespace Slic3r {
  20. // https://gist.github.com/gchudnov/6a90d51af004d97337ec
  21. namespace internal {
  22. namespace format {
  23. // Default "cook" function - just forward.
  24. template<typename T>
  25. inline T&& cook(T&& arg) {
  26. return std::forward<T>(arg);
  27. }
  28. // End of the recursive chain.
  29. inline std::string format_recursive(boost::format& message) {
  30. return message.str();
  31. }
  32. template<typename TValue, typename... TArgs>
  33. std::string format_recursive(boost::format& message, TValue&& arg, TArgs&&... args) {
  34. // Format, possibly convert the argument by the "cook" function.
  35. message % cook(std::forward<TValue>(arg));
  36. return format_recursive(message, std::forward<TArgs>(args)...);
  37. }
  38. }
  39. };
  40. template<typename... TArgs>
  41. inline std::string format(const char* fmt, TArgs&&... args) {
  42. boost::format message(fmt);
  43. return internal::format::format_recursive(message, std::forward<TArgs>(args)...);
  44. }
  45. template<typename... TArgs>
  46. inline std::string format(const std::string& fmt, TArgs&&... args) {
  47. boost::format message(fmt);
  48. return internal::format::format_recursive(message, std::forward<TArgs>(args)...);
  49. }
  50. } // namespace Slic3r
  51. #endif // slic3r_format_hpp_