c++ - 避免缩小 bitset 模板的转换

标签 c++

如何以可移植的方式编写以下内容以避免缩小转换?

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

live example

关于c++ - 避免缩小 bitset 模板的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40451241/

相关文章:

c++ - 无法编译,需要左值,在函数 main 中

c++ - glVertexAttribPointer 问题(OpenGL 3.x 向前兼容上下文)

C++ 将 Boost Regex 匹配结果转换为其他格式

c++ - 单例翻译单元混淆

c++ - 为什么跨线程更改共享变量的代码显然不会受到竞争条件的影响?

C++友元类

c++ - 从 "parent"项指针获取 `std::tuple` "children"

c++ - 为什么 ifstream 读取 0x80000000 的 int 失败

c++ - 应用GUI开发平台

c++ - 将指向堆栈变量的指针传递给 realloc() 是否有效?