Skip to content

Add upper-bound overflow checker for StaticCast #454

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

Merged
merged 1 commit into from
Jul 14, 2025

Conversation

chiphogg
Copy link
Member

This completes our overflow checking capabilities for StaticCast, in
the obvious way.

Note that we have a different set of subtleties to wrestle with than for
the min. For the min, we had to deal with unsigned types having a lower
bound of 0, although the signed types' lower bounds were nice powers of
two. For the max, in this PR, we have to watch out for the upper bounds
being slightly lower than a nice power of two. This has surprising
consequences, such as the fact that you can cast an int type's max to a
floating point type, but you can't cast it back. We deal with these
as best we can, bearing in mind that many common tools for dealing with
floating point types are not available in constexpr for C++14.

Helps #349.

This completes our overflow checking capabilities for `StaticCast`, in
the obvious way.

Note that we have a different set of subtleties to wrestle with than for
the min.  For the min, we had to deal with unsigned types having a lower
bound of 0, although the signed types' lower bounds were nice powers of
two.  For the max, in this PR, we have to watch out for the upper bounds
being _slightly lower_ than a nice power of two.  This has surprising
consequences, such as the fact that you can cast an int type's max to a
floating point type, but you _can't cast it back_.  We deal with these
as best we can, bearing in mind that many common tools for dealing with
floating point types are not available in `constexpr` for C++14.

Helps #349.
return x;
}

// `value()` implementation simply computes the result _once_ (caching it), and then returns it.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where does the caching come in? Is it just something that compiler can do when the result is a constexpr?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's what I was going for here.

@chiphogg chiphogg merged commit f73b87d into main Jul 14, 2025
14 checks passed
@chiphogg chiphogg deleted the chiphogg/overflow-max-good-static-cast#349 branch July 14, 2025 18:06
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

Successfully merging this pull request may close these issues.

2 participants