diff --git a/README.md b/README.md index 3e53871..63c2c8c 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,27 @@ We support Visual Studio, macOS, Linux, freeBSD. We support big and little endia We assume that the rounding mode is set to nearest (`std::fegetround() == FE_TONEAREST`). +## C++20: compile-time evaluation (constexpr) + +In C++20, you may use `fast_float::from_chars` to parse strings +at compile-time, as in the following example: + +```C++ +// consteval forces compile-time evaluation of the function in C++20. +consteval double parse(std::string_view input) { + double result; + auto answer = fast_float::from_chars(input.data(), input.data()+input.size(), result); + if(answer.ec != std::errc()) { return -1.0; } + return result; +} + +// This function should compile to a function which +// merely returns 3.1415. +constexpr double constexptest() { + return parse("3.1415 input"); +} +``` + ## Using commas as decimal separator diff --git a/tests/example_test.cpp b/tests/example_test.cpp index f2a0bce..91437de 100644 --- a/tests/example_test.cpp +++ b/tests/example_test.cpp @@ -43,6 +43,22 @@ void many_loop() { } } +#if FASTFLOAT_IS_CONSTEXPR +// consteval forces compile-time evaluation of the function in C++20. +consteval double parse(std::string_view input) { + double result; + auto answer = fast_float::from_chars(input.data(), input.data()+input.size(), result); + if(answer.ec != std::errc()) { return -1.0; } + return result; +} + +// This function should compile to a function which +// merely returns 3.1415. +constexpr double constexptest() { + return parse("3.1415 input"); +} +#endif + int main() { const std::string input = "3.1416 xyz "; double result; @@ -55,5 +71,10 @@ int main() { return EXIT_FAILURE; } many_loop(); +#if FASTFLOAT_IS_CONSTEXPR + if constexpr(constexptest() != 3.1415) { + return EXIT_FAILURE; + } +#endif return EXIT_SUCCESS; }