Merge pull request #188 from fastfloat/dlemire/compile_time

Compile-time evaluation
This commit is contained in:
Daniel Lemire 2023-03-27 13:51:27 -04:00 committed by GitHub
commit 0cdf016847
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -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`). 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 ## Using commas as decimal separator

View File

@ -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() { int main() {
const std::string input = "3.1416 xyz "; const std::string input = "3.1416 xyz ";
double result; double result;
@ -55,5 +71,10 @@ int main() {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
many_loop(); many_loop();
#if FASTFLOAT_IS_CONSTEXPR
if constexpr(constexptest() != 3.1415) {
return EXIT_FAILURE;
}
#endif
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }