[英]c++ auto type signed to/from unsigned conversion
我想编写一个函数,对auto
类型的参数执行按位操作。
unsigned int
或int
类型(具有不同的宽度)。 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.