C 自动类型签名到/从未签名的转换签名

c++ auto type signed to/from unsigned conversion

本文关键字:转换 类型      更新时间:2023-10-16

我想编写一个在auto类型的参数上执行位的功能。

  • 传递的类型可能是unsigned intint类型(宽度不同(。
  • 我只想在unsigned类型上执行位置操作。

我需要一个返回原始数据类型的unsigned版本的操作员。在下面的功能示例中,"运算符" unsigned_type将为我提供value具有的数据类型,但请确保其未签名。

  • int-> unsigned int
  • int16_t-> uint16_t
  • uint16_t-> uint16_t

功能示例:

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);
}

是否有一些手段来对从decltype获得的数据类型执行操作unsigned_type

谢谢。

c 11在<type_traits>中具有std::make_unsigned实用程序:

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);
}

使用C 14,您可以使用std::make_unsigned_t而不是std::make_unsigned::type

make_unsigned,如jarod42所说。

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

这不是您要使此函数类型依赖性的方式。使用模板,除非此功能是lambda。

这不需要标准中的功能。它根据VC 17启用了VS 2017的编译。

#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;
}