C 自动类型签名到/从未签名的转换签名
c++ auto type signed to/from unsigned conversion
我想编写一个在auto
类型的参数上执行位的功能。
- 传递的类型可能是
unsigned int
或int
类型(宽度不同(。 - 我只想在
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;
}
相关文章:
- 无法转换类型 C++
- 包含可变参数包的第一个可转换类型的别名的结构
- 将 std::conditional 与不可转换类型(原始与指针)一起使用
- 链接方法时出现转换类型错误
- 如何避免隐式转换类型
- 在多重继承场景中动态强制转换类型
- 编译器不支持的转换类型
- 错误调用功能无法转换类型
- 我想看到一个在整个后缀表达式的上下文中查找转换类型 id 的示例
- 对于动态类型为强制转换类型的对象,dynamic_cast失败
- 无法在初始化中转换类型
- 如何让"auto"转换类型
- 如何通过强制转换类型指针将字符数组转换为uint16_t
- 如何从新运算符+(Template类)返回具有转换类型的对象
- 带有模板的基于枚举的工厂无法转换类型
- 使用SWIG类型映射通过字符串转换类型
- 对于可转换类型,设计比循环依赖项更好
- SWIG不能正确转换类型定义
- 将类型转换扩展到可转换类型的对/元组
- 想要将字符数组的部分转换/类型转换为值