Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a type that can hold a uintptr_t or a uint32_t without a union?

How can I define a type uintptr such that it can hold at least a uint32_t and a uintptr_t, without resorting to a union?

Were sizeof() allowed in the preprocessor, this would accomplish what I want:

#include <inttypes.h>
#if sizeof(uint32_t) > sizeof(uintptr_t)  // unlikely, but the standard allows it
    typedef uint32_t uintptr;  
#else
    typedef uintptr_t uintptr;
#endif

It is extremely likely that uint32_t will be smaller if not equal to uintptr_t but the standard makes no guarantee. That said, such a platform would be very rare, so for now I've solved this by just having the following:

static_assert(sizeof(uint32_t) <= sizeof(uintptr_t), "Yikes");
typedef uintptr_t uintptr;
like image 946
Anne Quinn Avatar asked Feb 01 '26 03:02

Anne Quinn


1 Answers

There's no need for the preprocessor to get such an alias. It's a simple use case for the standard library's type traits

using uintptr = std::conditional_t<(sizeof(uint32_t) > sizeof(uintptr_t)),
                                   uint32_t, uintptr_t>;
like image 129
StoryTeller - Unslander Monica Avatar answered Feb 02 '26 17:02

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!