I want to write a function that performs bit-wise operations on a parameter that is auto type.
unsigned int or int type (with differing widths).unsigned types.I need an operator that returns the unsigned version of the original data type. In the function example below the "operator" unsigned_type would give me the data type that value has but insure it is unsigned.
int -> unsigned intint16_t -> uint16_tuint16_t -> uint16_tFunction example:
auto bit_shifting_and_mask(auto value) -> decltype(value)
{
unsigned_type(value) unsigned_value = static_cast<unsigned_type(value)>(value);
unsigned_value >>= 8u; // Contrived bit manipulation
unsigned_value &= 0xABCDu; // here ...
return static_cast<decltype(value)>(unsigned_value);
}
Is there some means to perform the operation unsigned_type against a data type obtained from decltype?
Thanks.
C++11 has a std::make_unsigned utility in <type_traits>:
auto bit_shifting_and_mask(auto value) -> decltype(value)
{
auto unsigned_value = static_cast<std::make_unsigned<decltype(value)>::type>(value);
unsigned_value >>= 8u; // Contrived bit manipulation
unsigned_value &= 0xABCDu; // here ...
return static_cast<decltype(value)>(unsigned_value);
}
With C++14, you can simplify further by using std::make_unsigned_t instead of std::make_unsigned::type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With