【发布时间】:2015-07-06 08:29:43
【问题描述】:
下面的代码生成带有-Wsign-conversion 的警告。它会在T digit = a % base 行生成警告。
我想提取 T 的签名,然后将 base 转换为该签名以消除警告。
我试图避免专业化,因为这只会重复代码(唯一要改变的是base 的签名)。我还试图避免将base 转换为T,以防它是像Integer 这样的非POD 类型(针对longs 的减少进行了优化)。
如何提取T 的签名?
相关,代码库实际上是 C++98 和 C++03,因此它没有某些特性(如在 Partial template specialization based on “signed-ness” of integer type? 中讨论的)。
template <class T>
std::string IntToString(T a, unsigned int base = 10)
{
if (a == 0)
return "0";
bool negate = false;
if (a < 0)
{
negate = true;
a = 0-a; // VC .NET does not like -a
}
std::string result;
while (a > 0)
{
T digit = a % base;
result = char((digit < 10 ? '0' : ('a' - 10)) + digit) + result;
a /= base;
}
if (negate)
result = "-" + result;
return result;
}
【问题讨论】:
-
在您的情况下,应将
a转换为unsigned。 (它会修复边缘情况(IntToString<signed char>(-128))。 -
C++11 类型特征库来自 boost。我强烈建议使用 C++98/03 中的 Boost.TypeTraits 库,而不是推出自己的元函数。
-
@sbabbi - 该库使用 C++03,并且没有外部依赖项。此外,Boost 无法通过验收测试。最后,Boost 不适用于某些基于 Windows 的配置。
标签: c++ templates unsigned signed