How to guarantee compile-time evaluation of algorithm while allowing runtime invocation as well

Viewed 95

I have a hash function, I want to implement it with C++20 consteval to make sure the inputs I want to be evaluated at compile time will be done before runtime. That's for the constants and hardcoded content. However, later I need to compare them with runtime/dynamic variables, for the equals() to work I have to calculate the hash of the runtime variable and I need to invoke the very same algorithm from runtime.

The instinct is the implement it twice (one for compile-time and one for runtime), but it feels wrong to duplicate the code when it's in essence the same algorithm/code. Is there a smarter way (template variable or something) to have one algorithm which can be instantiated for both purposes as needed?

The C++14 and higher have a lot of great features and wondering if something slipped my mind. Preferably I would like to use the pure C++ features and avoid helper libs like std boost etc...

1 Answers

How to guarantee compile-time evaluation of algorithm while allowing runtime invocation as well

Write your function as a constexpr one, and then, if you want to guarantee a particular result is done at compile-time, write the result into a constexpr variable:

constexpr int f(...) { ... }

constexpr int compile_time_result = f(...);

You will get an error if the result couldn't be computed at compile-time.

If you don't care, take out the constexpr of the variable:

int maybe_runtime_result = f(...);
Related