下面的代码使用 -Wsign-conversion
生成警告。它在 T digit = a % base
行生成警告。
我想提取 T
的签名,然后将 base
转换为该签名以消除警告。
我试图避免专门化,因为那只会重复代码(唯一要改变的是 base
的签名)。我还试图避免将 base
转换为 T
以防它是非 POD 类型,如 Integer
(针对使用 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;
}
最佳答案
C++11 之前你可以使用 std::conditional
的这个实现:
template<bool B, class T, class F>
struct conditional { typedef T type; };
template<class T, class F>
struct conditional<false, T, F> { typedef F type; };
然后我们可以编写一个结构来提取类型的符号:
template <typename T>
struct signedness {
typedef typename conditional<T(-1)<T(0),int,unsigned>::type type;
};
然后只需将 base
声明为该类型即可:
std::string IntToString(T a,
typename signedness<T>::type base = 10){
关于c++ - 提取模板类型的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241077/