通过模板对unsigned int的C++限制

标签 c++ templates stl binary limits

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

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/

相关文章:

c++ - 如何用链表替换 vector C++

c++ - 我应该/可以/必须如何处理我的 C++ 项目所依赖的 dll?

python - Mako 模板内联 if 语句

c++ 带有静态变量的静态函数的奇怪行为

c++ - C++中的模板成员函数

c++ - 如何使用内部类类型初始化模板类中的静态字段

C++设置: counting elements less than a value

c++ - 如何连接几张 map ?

c++ - 我应该返回 gsl::span<const T> 而不是 const std::vector<T>&

c++ - 编译库与仅 header 库