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.
Parsing Numbers At Compile Time with C++17, C++23, and C++26
by Bartlomiej Filipek
From the article:
Why at compile time?
While it may sound like a theoretical experiment, since C++11 we can shift more and more computations to compile-time. Here are some key areas and examples where
constexpr
can be beneficial:
- Building lookup tables
- Working with embedded resources (like fonts or bitmaps)
- Parsing configuration strings
- Regular Expressions at compile time
- Working with bit flags and bits
- UB program verification (
constexpr
context guarantees no UB in your code)- and many more… see Your New Mental Model of constexpr - Jason Turner - CppCon 2021 - YouTube or Lightning Talk: Memoizing Constexpr Programs - Chris Philip - CppCon 2021 - YouTube or Anything can be a Constexpr if you try hard enough - Zoe Carver - CppCon 2019 - YouTube
Starting easy from C++17
Starting with C++17, we are now capable of writing complex
constexpr
functions. However, our ability to do so is still limited by the range of algorithms available in that context. Luckily, with the introduction ofstring_view
in that version of C++, there is no longer any need to work with “raw”const char*
buffers.
Add a Comment
Comments are closed.