Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
adleret221 opened this issue May 14, 2018 · 4 comments
Open

Comments

@adleret221
Copy link

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.

@elbeno
Copy link
Owner

elbeno commented May 15, 2018

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.

@LB--
Copy link

LB-- commented May 15, 2018

Well there is P1073R0 that we might have some day.

@DanielJump
Copy link

DanielJump commented Mar 5, 2021

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

@LB--
Copy link

LB-- commented Mar 9, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants