//https://docs.microsoft.com/en-us/archive/msdn-magazine/2015/march/windows-with-c-using-printf-with-modern-c
inline void Print(char const * const value) noexcept
{
Print("%s", value);
}
inline void Print(wchar_t const * const value) noexcept
{
Print("%ls", value);
}
template <typename T>
void Print(std::basic_string<T> const & value) noexcept
{
Print(value.c_str());
}
template <typename T>
T const * Argument(std::basic_string<T> const & value) noexcept
{
return value.c_str();
}
template <typename T>
T Argument(T value) noexcept
{
return value;
}
template <typename ... Args>
void Print(char const * const format,
Args const & ... args) noexcept
{
printf(format, Argument(args) ...);
}
template <typename ... Args>
int StringPrint(char * const buffer,
size_t const bufferCount,
char const * const format,
Args const & ... args) noexcept
{
int const result = snprintf(buffer,
bufferCount,
format,
Argument(args) ...);
ASSERT(-1 != result);
return result;
}
template <typename ... Args>
int StringPrint(wchar_t * const buffer,
size_t const bufferCount,
wchar_t const * const format,
Args const & ... args) noexcept
{
int const result = swprintf(buffer,
bufferCount,
format,
Argument(args) ...);
ASSERT(-1 != result);
return result;
}
template <typename T, typename ... Args>
void Format(std::basic_string<T> & buffer,
T const * const format,
Args const & ... args)
{
size_t const size = StringPrint(&buffer[0],
buffer.size() + 1,
format,
args ...);
if (size > buffer.size())
{
buffer.resize(size);
StringPrint(&buffer[0], buffer.size() + 1, format, args ...);
}
else if (size < buffer.size())
{
buffer.resize(size);
}
}
inline std::string ToString(wchar_t const * value)
{
std::string result;
Format(result, "%ls", value);
return result;
}
inline std::string ToString(double const value,
unsigned const precision = 6)
{
std::string result;
Format(result, "%.*f", precision, value);
return result;
}
使用c++11 + 来优化常见的printf 和sprintf 操作
最新推荐文章于 2024-07-16 08:11:24 发布