all. Very quick question. Why statement like below can be compiled with recent gcc or MSVC, but same thing with custom types is not possible?
const auto& a = isParamFP16 ? 0 : "aaa";
- possible
const auto& a = isParamFP16 ? paramFP32 : paramFP16;
- impossible (error C2446: ':': no co nversion from 'const T' to 'const T'
for MSVC and operands to ?: have different types ‘const param<FP32>’ and ‘const param<FP16>’
for gcc)
I know that all types should be resolved at compile time, but why first variant works?
Thank you.
CodePudding user response:
With
const auto& a = isParamFP16 ? 0 : "aaa";
"aaa"
's type will decay to a const char *
. 0
is an int
, but it is also a valid value for a const char *
since it is a null pointer constant. That means the compiler will deduce the entire conditional operation as yielding a const char *
no matter which value is returned.
With
const auto& a = isParamFP16 ? paramFP32 : paramFP16;
You have a param<FP32>
for the first result and a param<FP16>
for the second. There is no way to convert one to the other, so a compiler error is issued as the conditional operator can only yield a single type.
CodePudding user response:
The first variant works, because an integer literal 0
is a null pointer constant, which means it can be implicitly converted to any pointer type (resulting in a null pointer value).
So, 0
can be converted to const char*
and the string literal "aaa"
decays to a pointer const char*
. The types match, and so the type of a
will be char const* const&
.
Try it with any other value, e.g. 1
or some math e.g. 1-1
, and it won't compile.
CodePudding user response:
The last two operands of the ? expression must have identical types (to an implicit conversion) so that the type of the whole expression can be deduced at compile-time. In the first case they do (pointer). Not in the second.