Add dtype::normalized_num and dtype::num_of #5429
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This commit adds two functions,
dtype::normalized_num
anddtype::num_of
, which make it possible to use a switch statement for dynamic dispatch based on the dtype of an array, like this:dtype::normalized_num
does the same asdtype::num
, except the type number is normalized to match the one used innpy_format_descriptor
. This is needed becausedtype::num
can return different values for equivalent types, e.g. even thoughlong
may be equivalent toint
orlong long
, they still have different type numbers (at least when the dtype is constructed by type number, rather than withdtype::of<T>()
). Without normalization, this leads to strange bugs where the switch statement inexplicably rejects arrays from certain sources despite superficially having the correct dtype. E.g. on x86_64 (linux), dtypeslong
(7) andlonglong
(9) both appear asint64
but have different type numbers:dtype::num_of<T>
is simply the constexpr equivalent ofdtype::of<T>().num()
, so it can be used for cases in a switch statement.While developing this, I ran into an inconsistency in the behavior of
is_fmt_numeric
which is relevant for the implementation ofdtype::normalized_num
, I have reported this as a separate issue: #5428Suggested changelog entry:
Add dtype::normalized_num and dtype::num_of