fenbf / cppstories-discussions

4 stars 1 forks source link

2024/constexpr-number-parsing-cpp23/ #137

Open utterances-bot opened 9 months ago

utterances-bot commented 9 months ago

Parsing Numbers At Compile Time with C++17, C++23, and C++26 - C++ Stories

Thanks to the powerful constexpr keyword and many enhancements in recent C++ standards, we can now perform a lot of computations at compile time. In this text, we’ll explore several techniques for parsing integers, including the “naive” approach, C++23, from_chars, std::optional, std::expected, and even some upcoming features in C++26. But first… why would this even be needed?

https://www.cppstories.com/2024/constexpr-number-parsing-cpp23/

2kaud commented 9 months ago

The C++23 version using std::optional can be 'simplified'. See https://godbolt.org/z/WdThsjYzK

Also similar with the std::expected version.

Note that in this version static_assert(tryParseIntCpp23(" 6789abc").value() == 6789);

does not assert (as the string is not wholly an integer), but does assert in the original.

fenbf commented 9 months ago

Thanks for the comment and for the code. My parsing routines have "loose" requirements, but your code is also looking fine. It's probably nicer than mine and shorter.

2kaud commented 9 months ago

I note that the c++ functions isxxx() and toyyy() (defined in cctype) are still not constexpr. This is probably because many are locale specific. For working in just ASCII with unsigned 8-bit chars, we use these as replacement which are constexpr. These are also faster! See https://godbolt.org/z/zdTM3KhMj This defines these functions for char 0 - 127 but the method is easily extended to 0 - 255 and to add other isxxx() or toyyy() functions as needed.