constexpr
constexpr copied to clipboard
The use of "return true ? <object> : <exception>" syntax in code
I was wondering as to the nature of the syntax appearing many times in your code, with the use of the ternary operator, for example:
return true ? detail::md5::md5(s) : throw err::md5_runtime_error;
What is the benefit of this? why not just return detail::md5::md5(s)
?
After all, to my understanding, the exception will never be evaluated at runtime. Maybe there is some added value to this at compile time? If so, what is it?
thank you in advance.
This is Scott Schurr's link-time hack that attempts to prevent accidental non-constexpr usage of a function. The idea is that if you accidentally call a function in a non-constexpr context, it will reference a symbol that is not defined and cause a link error. Notice that everything that is thrown is externed, but not defined anywhere.
This is definitely not portable, but it works (worked?) on some compilers. I hope in future there will be better ways to guard against non-constexpr usage. The constexpr parts of C++ are evolving fast at the moment, so this repo is a dated experiment at this point.
Well there is P1073R0 that we might have some day.
Unfortunately, this doesn't work on MSVC anymore. cx_sha256.h(24,26): error C7631: 'cx::err::`anonymous-namespace'::sha256_runtime_error': variable with internal linkage declared but not defined
It's also a warning on clang (-Wundefined-internal) but that can be disabled.
This thread has some ideas - could we use one of those instead? https://stackoverflow.com/questions/39650122/how-to-ensure-constexpr-function-never-called-at-runtime
There is consteval
in the C++20 standard now: https://en.cppreference.com/w/cpp/language/consteval