[英]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.