Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Courtesy of https://msdn.microsoft.com/en-us/magazine/dn913181.aspx
- // Kenny Kerr
- #include <string>
- #include <cassert>
- using namespace std::literals::string_literals;
- template <typename T>
- T Argument(T value) noexcept {
- return value;
- }
- template <typename T>
- T const * Argument(std::basic_string<T> const & value) noexcept {
- return value.c_str();
- }
- 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;
- }
- 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));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement