Last active
January 30, 2022 08:42
-
-
Save voidbar/d225bde7a7ba92f47294ae020a360643 to your computer and use it in GitHub Desktop.
Number to string function using constexpr lamba with auto deductible parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <charconv> | |
#include <iostream> | |
#include <array> | |
constexpr auto ToString = [](auto number) constexpr -> const std::string { | |
std::array<char, 20 /* Max chars in 64 bit number*/> buffer; | |
if (auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), number); ec == std::errc()) | |
{ | |
return std::string{buffer.data(), static_cast<size_t>(ptr - buffer.data())}; | |
} | |
return {}; | |
}; | |
int main() { | |
std::cout << "\"1234.123\": " << ToString(1234.123) << "\n"; | |
std::cout << "\"1234\": " << ToString(1234) << "\n"; | |
std::cout << "\"0.0f\": " << ToString(0.0f) << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment