gcc 奇怪的转换警告(<B>从"int"转换为"A::count_type {aka short unsigned int}"可能会改变其值)
gcc weird conversion warning (conversion to ‘A<B>::count_type {aka short unsigned int}’ from ‘int’ may alter its value)
我有以下使用模板的C++11代码:
struct Base{
using count_type = unsigned short;
};
template<class T>
struct A : public Base{
using count_type = A::count_type;
// not works even if I comment this
count_type add(T x){
count_type sum = 5;
sum += x.value();
//sum += (count_type) x.value(); // not works even if I cast this, e.g.
return sum;
}
};
struct B{
using count_type = A<B>::count_type;
count_type value(){
return 5; // not works even if I do:
//return (count_type) 5;
//return 5U;
}
};
int main(int argc, char *argv[]){
B b;
A<B> a;
a.add(b);
}
当我尝试用-Wconversion
编译时,我收到了一条奇怪的错误消息:
$ g++ -std=c++11 -Wconversion x.cc
x.cc: In instantiation of ‘A<T>::count_type A<T>::add(T) [with T = B; A<T>::count_type = short unsigned int]’:
x.cc:29:9: required from here
x.cc:11:7: warning: conversion to ‘A<B>::count_type {aka short unsigned int}’ from ‘int’ may alter its value [-Wconversion]
sum += x.value();
^
为什么会发生这种情况?哪里没有int
?
如果有人修改我的问题,我将不胜感激。
注:clang
未给出此警告。
sum += x.value();
的意思(大致)是sum = sum + x.value();
这里的RHS sum + x.value()
将两个unsigned short
值相加,生成一个int
。将该int
分配回unsigned short
可以改变其值。
在我看来,这个警告不是特别有用,我建议关闭它,但如果你出于某种原因想保持它的启用状态,请在那里写一个演员阵容:
sum = (count_type) (sum + x.value());
或
sum = static_cast<count_type>(sum + x.value());
根据隐式提升,任何算术表达式(如sum = sum + x.value()
)都会经历一种称为常规算术转换的模式,该模式是标准§5中的相关部分:
--否则,应对两个操作数执行积分提升(4.5)。59然后,以下规则应适用于提升的操作数:
整体促销规定:
如果int可以表示源类型的所有值,则其整数转换秩(4.13)小于int的秩的除bool、char16_t、char32_t或wchar_t之外的整数类型的prvalue可以转换为类型
int
的prvalue;否则,源prvalue可以转换为unsigned int类型的prvalue。
因此,操作数被转换为int
,然后返回到unsigned short
。这是因为转换等级指定
有符号整数类型的秩应大于任何大小较小的有符号整数型的秩。
和
任何无符号整数类型的秩都应等于相应的有符号整数类型。
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度