top of page

Constexpr function parameters

Hi C++ Fans!


Last week I asked you how you would pass a contexper parameter to a function.

The problem is that most parameters to a function are considered to be known only during run-time, so they cannot be used in constant evaluation.


But don't worry, there is a fix to that problem, and some of those solutions were provided by you guys; thank you, David Amar and Ron Sider; your answers were the closest to what I had in mind.


Today I will publish two ways to do it and still make it look like a pure function.


Implementation 1: here, we will use the c++20 auto concept in function parameters and the fact that lambdas will be constexpr if possible (since c++17); the function receives a lambda, so the compiler is sure that this type is constexpr, and we can use it in constexpr evaluation.


Implementation 2: this implementation uses C++20 of non-type template parameters, allowing the compiler to deduce the parameter and enforce it to be a constant expression.


Implementation 2 is more straightforward, in my opinion; what do you think?



Comments


bottom of page