Skip to content

Commit 0cdf016

Browse files
authored
Merge pull request #188 from fastfloat/dlemire/compile_time
Compile-time evaluation
2 parents 3ada7ca + d7ba016 commit 0cdf016

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+21
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,27 @@ We support Visual Studio, macOS, Linux, freeBSD. We support big and little endia
7272

7373
We assume that the rounding mode is set to nearest (`std::fegetround() == FE_TONEAREST`).
7474

75+
## C++20: compile-time evaluation (constexpr)
76+
77+
In C++20, you may use `fast_float::from_chars` to parse strings
78+
at compile-time, as in the following example:
79+
80+
```C++
81+
// consteval forces compile-time evaluation of the function in C++20.
82+
consteval double parse(std::string_view input) {
83+
double result;
84+
auto answer = fast_float::from_chars(input.data(), input.data()+input.size(), result);
85+
if(answer.ec != std::errc()) { return -1.0; }
86+
return result;
87+
}
88+
89+
// This function should compile to a function which
90+
// merely returns 3.1415.
91+
constexpr double constexptest() {
92+
return parse("3.1415 input");
93+
}
94+
```
95+
7596
## Using commas as decimal separator
7697
7798

tests/example_test.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,22 @@ void many_loop() {
4343
}
4444
}
4545

46+
#if FASTFLOAT_IS_CONSTEXPR
47+
// consteval forces compile-time evaluation of the function in C++20.
48+
consteval double parse(std::string_view input) {
49+
double result;
50+
auto answer = fast_float::from_chars(input.data(), input.data()+input.size(), result);
51+
if(answer.ec != std::errc()) { return -1.0; }
52+
return result;
53+
}
54+
55+
// This function should compile to a function which
56+
// merely returns 3.1415.
57+
constexpr double constexptest() {
58+
return parse("3.1415 input");
59+
}
60+
#endif
61+
4662
int main() {
4763
const std::string input = "3.1416 xyz ";
4864
double result;
@@ -55,5 +71,10 @@ int main() {
5571
return EXIT_FAILURE;
5672
}
5773
many_loop();
74+
#if FASTFLOAT_IS_CONSTEXPR
75+
if constexpr(constexptest() != 3.1415) {
76+
return EXIT_FAILURE;
77+
}
78+
#endif
5879
return EXIT_SUCCESS;
5980
}

0 commit comments

Comments
 (0)