
[英]error C4146: unary minus operator applied to unsigned type, result still unsigned
[英]error unary minus operator applied to unsigned type results in unsigned
我目前在我的代码中有一个将数字类型转换为字符串的函数。由于我没有使用std::to_string
。 现在,此代码可以在XCode上很好地构建,但是窗口似乎在抱怨。 Windows抱怨的原因是,在某一时刻我传递了一个无符号类型,然后对该类型执行否定操作,因为该类型为无符号类型,所以仍然保持肯定状态。 我的问题是我可以放置一个if类来检查类型是否已签名,然后输入条件吗? 这会解决问题吗
template<typename t>
std::string MyFunct(t num,int base=10)
{
char str [sizeof(t)*8+1];
int i = 0;
bool isNegative = false;
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
return str;
}
//Negative only when base is 10
if (num < 0 && base == 10)
{
isNegative = true;
num = -num; //<------ERROR in case the type is unsigned
}
....
....
}
我怎样才能解决这个问题 ? 只有在类型为无符号的情况下,我才可以告诉编译器吗?
对于支持C ++ 17的现代编译器, constexpr if
将其与std::numeric_limits<T>::is_signed
一起使用 , 则只能使用constexpr if
来仅对有符号整数类型执行取反。 请注意,普通if
仍可能会导致编译器进行诊断,而constexpr if
是必需的。
constexpr if
的替代方法是相当简单的模板专门化:
template<typename t, bool is_signed=std::numeric_limits<T>::is_signed>
std::string MyFunct(t num,int base=10);
template<typename t>
std::string MyFunct<t, true>(t num,int base10)
{
// The signed specialization of MyFunct()
}
template<typename t>
std::string MyFunct<t, false>(t num,int base)
{
// The unsigned specialization of MyFunct()
}
只有转换函数的带符号版本会使用取反逻辑。 当然,函数的有符号版本和无符号版本都会有很多共同的代码。 但是现在,通过简单,直接的重构,这已成为一种普通情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.