C++通过模板限制 unsigned int
我正在使用模板将整数类型转换为其二进制值的字符串表示形式。我使用了以下内容:
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
I'm using a template to convert integral types into a string representation of their binary values. I used the following:
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;
}
It works for int but doesn't compile with 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
Could you explain why?
EDIT:
Yes, I'm using VS2010
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是您的 ToBinary 调用是不明确的,而是具有无符号值的 bitset 的构造函数调用。不幸的是,这是一个 VC++ Bug: http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc
编辑 - 解决方法:
Not your ToBinary call is ambiguous, its the constructor call of bitset with an unsigned value. Unfortunately this is a VC++ Bug: http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc
Edit - Workaround:
如果您查看标准 (FDIS n3290),您会发现
std::bitset
有多个构造函数:第一个是:
20.5.1 bitset 构造函数 [bitset.cons]< /强>
然后还有这个,我怀疑当您使用
unsigned int
调用它时,这可能会导致事情变得不明确If you look at the standard (FDIS n3290), then you see that
std::bitset
has multiple constructors:First there is this one:
20.5.1 bitset constructors [bitset.cons]
Then there is also this one, which I suspect might be might cause things to become ambigious, when you call it with
unsigned int
你用的是VC10吗?已经报告了一个问题:Microsoft connect。 另外,我猜您可能可以通过将类型转换为 int (如果它是 32 位)来修复它,如下所示:
这可以在内部完成的如果需要的话也可以使用该方法。不过,重新解释的结果不应该再用于算术。 ;)
作为我的解决方法工作正常(但看起来很丑)
Are you using VC10? There is already an issue reported: Microsoft connect. Also I'd guess that you might be able to fix it by casting the type to int if it is 32 bit, like this:
This can be done inside of the method as well if needed. The result of the reinterpret should not be used for arithmetics anymore, though. ;)
Works fine as workaround for me (but looks quite ugly)