通过模板的无符号int的C++限制

Hei*_*bug 6 c++ binary templates limits stl

我正在使用模板将整数类型转换为二进制值的字符串表示形式.我使用了以下内容:

template<typename T>
std::string ToBinary(const T& value)
{
    const std::bitset<std::numeric_limits<T>::digits + 1> bs(value);
    const std::string s(bs.to_string());

    return s;
}
Run Code Online (Sandbox Code Playgroud)

它适用于int但不使用unsigned int编译:

unsigned int buffer_u[10];
int buffer_i[10];
...
ToBinary(buffer_i[1]); //compile and works
ToBinary(buffer_u[1]); //doesn't compile -- ambiguous overload
Run Code Online (Sandbox Code Playgroud)

你能解释一下原因吗?

编辑:

是的,我正在使用VS2010

Kas*_*asF 4

不是您的 ToBinary 调用是不明确的,而是具有无符号值的 bitset 的构造函数调用。不幸的是,这是一个 VC++ Bug:http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc

编辑 - 解决方法:

template<>
std::string ToBinary<unsigned int>(const unsigned int& value)
{
    const std::bitset<std::numeric_limits<unsigned int>::digits> bs(static_cast<unsigned long long>(value));
    return bs.to_string();
}
Run Code Online (Sandbox Code Playgroud)