避免对bitset模板进行窄化转换
Avoid narrowing conversion for bitset template
如何以可移植的方式编写以下代码以避免窄化转换?
#include <bitset>
#include <iostream>
#include <climits>
template <typename T>
auto int_to_bitset(T x)
{
//return std::bitset<sizeof(T)*CHAR_BIT>{x}; // does not work, narrowing conversion to unsigned type
//return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<unsigned int>(x)}; // might not have the same size as T
//return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<unsigned T>(x)}; // What I would like to do, but does not work. I've never seen so many errors.
return std::bitset<sizeof(T)*CHAR_BIT>(x); // works, but selects unsigned long long for the constructor's parameter on my system. Can this conversion be relied on?
}
int main()
{
std::cout << int_to_bitset<short>( 1 ) << 'n';
std::cout << int_to_bitset<short>(-1 ) << 'n';
std::cout << int_to_bitset ( 1 ) << 'n';
std::cout << int_to_bitset (-1 ) << 'n';
std::cout << int_to_bitset ( 1L ) << 'n';
std::cout << int_to_bitset (-1L ) << 'n';
std::cout << int_to_bitset ( 1LL) << 'n';
std::cout << int_to_bitset (-1LL) << 'n';
}
生产:
0000000000000001
1111111111111111
00000000000000000000000000000001
11111111111111111111111111111111
00000000000000000000000000000001
11111111111111111111111111111111
0000000000000000000000000000000000000000000000000000000000000001
1111111111111111111111111111111111111111111111111111111111111111
您可以使用std::make_unsigned
:
template <typename T>
auto int_to_bitset(T x)
{
return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<std::make_unsigned_t<T>>(x)};
}
生活例子
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 如何以滑动窗口方式从 std::bitset 读取位并将它们转换为 int?
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- 从文件中读取字符串并转换为 bitset<12>
- 将uint8_t的向量转换为bitset
- 将BITSet转换为ASCII字符串
- 如何使用库将二进制转换为十进制<bitset>?
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- 避免对bitset模板进行窄化转换
- 我如何将bitset转换为字节/uint8数组
- 如何在不指定位大小的情况下将字符串转换为bitset ?
- Std::string转换为Std::bitset,由Std::string表示,反之亦然