繁体   English   中英

c ++自动类型与无符号转换签名

[英]c++ auto type signed to/from unsigned conversion

我想编写一个函数,对auto类型的参数执行按位操作。

  • 传入的类型可能是unsigned intint类型(具有不同的宽度)。
  • 我只想对unsigned类型执行逐位运算。

我需要一个返回原始数据类型的unsigned版本的运算符。 在下面的函数示例中,“operator” 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 decltype

谢谢。

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。

这不需要标准中尚未(功能)的功能。 它在VS 2017下编译,启用VC ++ 17。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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