constexpr icon indicating copy to clipboard operation
constexpr copied to clipboard

The use of "return true ? <object> : <exception>" syntax in code

Open adleret221 opened this issue 6 years ago • 4 comments

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.

adleret221 avatar May 14 '18 13:05 adleret221

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.

elbeno avatar May 15 '18 01:05 elbeno

Well there is P1073R0 that we might have some day.

LB-- avatar May 15 '18 15:05 LB--

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

DanielJump avatar Mar 05 '21 19:03 DanielJump

There is consteval in the C++20 standard now: https://en.cppreference.com/w/cpp/language/consteval

LB-- avatar Mar 09 '21 00:03 LB--