以下代码使用-Wsign-conversion
生成警告。它在T digit = a % base
行生成警告。
我想提取T
的签名,然后将base
转换为该签名,以压榨警告。
我试图避免特化,因为这只会重复代码(唯一要更改的是base
的签名)。我还试图避免将base
转换为T
,以防其成为Integer
(已针对longs
进行了优化而优化)的非POD类型。
如何提取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/