Issue
We are now testing compiling some Qt code under QtCreator with the newer gcc 7.3 available in Ubuntu 18 (we were previously using gcc 4.9.3 under Ubuntu 16).
enum CheckState {
Unchecked,
PartiallyChecked,
Checked
};
Now, when we use the ternary operator with this:
QVariant MyClass::MyFunc(const QModelIndex &index, int role) const {
return (someCondition ? Qt::Checked : Qt::Unchecked);
}
then gcc
complains (with a warning, but we treat warnings as errors):
prog.cpp:999:99:
error: passing ‘Qt::CheckState’ chooses ‘int’
over ‘uint {aka unsigned int}’ [-Werror=sign-promo]
We can get around the issue with:
return (someCondition ? Qt::Checked : static_cast<int>(Qt::Unchecked));
but I'm not sure why that should be necessary.
Since these are coming from exactly the same enum
, they should be the same type, no? I know that there are potential issues where the two possible values are different types, but I can't understand why this type casting needs to be done in this case.
The values are {0, 1, 2}
from the enum
and I would have thought the exact same type negated any possibility for conversion.
The only possibility I can think of is the fact that the zero value of the enumeration is being treated as unsigned for some reason.
Solution
In lieu of an MCVE I am assuming the context is something like:
struct S
{
S(int);
S(unsigned int);
};
S foo()
{
return (1 ? Qt::Checked : Qt::Unchecked);
}
which produces warning in gcc 7.3:
warning: passing
Qt::CheckState
choosesint
overunsigned int
[-Wsign-promo]
The warning relates to the implicit conversion of value of type enum CheckState
to integer. There is valid implicit conversion to both int
and unsigned int
, and overload resolution selects int
.
Apparently the rationale for the warning is that some older versions of gcc selected unsigned int
in this scenario , but gcc 7 follows the Standard and selects int
.
Your fix works because the second and third operands are brought to a common type of int
before overload resolution occurs (it is not anything to do with which enumerator you chose).
Perhaps an appropriate fix would be to apply static_cast<int>
to the whole conditional, not just one operand.
Answered By - M.M Answer Checked By - Mildred Charles (WPSolving Admin)