简体   繁体   中英

c++ auto type signed to/from unsigned conversion

I want to write a function that performs bit-wise operations on a parameter that is auto type.

  • The type passed in might be unsigned int or int type (with differing widths).
  • I only want to perform bit-wise operations on 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 int
  • int16_t -> uint16_t
  • uint16_t -> uint16_t

Function 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 .

make_unsigned , as Jarod42 said.

auto bit_shifting_and_mask(auto value) -> decltype(value)

This is not the way you want to make this function type-dependent. Use template, unless this function is lambda.

This does not require features not (yet) in the standard. It compiles under VS 2017 with VC++17 enabled.

#include <type_traits>
template<typename T>
auto bit_shifting_and_mask(T value) {
    static_assert(std::is_integral_v<T>, 
        "bit_shifting_and_mask(value): value is not integral type");
    using unsgn =std::make_unsigned_t<T>;
    auto unsigned_value = static_cast<unsgn>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return unsigned_value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM