Skip to content

Commit

Permalink
Merge pull request #188 from fastfloat/dlemire/compile_time
Browse files Browse the repository at this point in the history
Compile-time evaluation
  • Loading branch information
lemire authored Mar 27, 2023
2 parents 3ada7ca + d7ba016 commit 0cdf016
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions tests/example_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}

0 comments on commit 0cdf016

Please sign in to comment.