我正在使用一个模板将整数类型转换为二进制值的字符串表示形式。我使用了以下内容:
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;
}
它适用于 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
你能解释一下为什么吗?
编辑:
是的,我正在使用 VS2010
最佳答案
不是您的 ToBinary 调用不明确,它是具有无符号值的 bitset 的构造函数调用。不幸的是,这是一个 VC++ 错误: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();
}
关于通过模板对unsigned int的C++限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001404/