mercredi 21 février 2018

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.

Aucun commentaire:

Enregistrer un commentaire