//Courtesy of https://msdn.microsoft.com/en-us/magazine/dn913181.aspx // Kenny Kerr #include #include using namespace std::literals::string_literals; template T Argument(T value) noexcept { return value; } template T const * Argument(std::basic_string const & value) noexcept { return value.c_str(); } template 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 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 void Format(std::basic_string& 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; } TEST(StringFormat, ConvertWideCharacterToString) { ASSERT_TRUE("hello"s == ToString(L"hello")); } TEST(StringFormat, ConvertDoubleToString) { ASSERT_TRUE("123.46"s == ToString(123.456, 2)); } TEST(StringFormat, ConvertFloatToString) { ASSERT_TRUE("123.457"s == ToString(123.45678f, 3)); }