RFR: 8377895: Create sizeof_auto, to reduce narrowing conversions [v2]

Albert Mingkun Yang ayang at openjdk.org
Mon Feb 23 18:46:03 UTC 2026


On Wed, 18 Feb 2026 09:41:31 GMT, Leo Korinth <lkorinth at openjdk.org> wrote:

>> I remembered enough of the trick to think it probably doesn't work here.  However, there's a variant, using C++17 features, that I think probably would work.  But I didn't explore in that direction because I realized there's a *much* simpler approach; just use `sizeof` to deal with that dispatch.  Here's my (untested, hopefully no syntax errors) solution:
>> 
>> template<size_t N>
>> constexpr auto sizeof_auto_impl() {
>>   using unsigned_auto =
>>     std::conditional_t<N <= std::numeric_limits<uint8_t>::max(), uint8_t,
>>       std::conditional_t<N <= std::numeric_limits<uint16_t>::max(), uint16_t,
>>         std::conditional_t<N <= std::numeric_limits<uint32_t>::max(), uint32_t, uint64_t>>>;
>>   return static_cast<unsigned_auto>(N);
>> }
>> #define sizeof_auto(...) sizeof_auto_impl<sizeof(__VA_ARGS__)>()
>
> I think your solution is the very best solution. I will use it.

This is probably subjective. I find this nested `conditional_t` rather hard to parse/follow. I wonder what you think of `if constexpr`.


template<size_t N>
constexpr auto sizeof_auto_impl() {
    if constexpr (N <= 0xFF)       return uint8_t(N);
    if constexpr (N <= 0xFFFF)     return uint16_t(N);
    if constexpr (N <= 0xFFFFFFFF) return uint32_t(N);
    return uint64_t(N);
}

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/29716#discussion_r2842468602


More information about the hotspot-dev mailing list