In C++, I'm trying to use implicit conversion with a conditional operator. Consider this example:
class MyFloat
{
public:
MyFloat(float val){m_val = val;}
operator float(){return m_val;}
protected:
float m_val;
};
int main(int argc, char **argv)
{
MyFloat a = 0.5f;
MyFloat b = 1.0f;
float x = true ? a-0.5f : b;
return 0;
}
It causes a compiler error:
error: operands to ?: have different types ‘MyFloat’ and ‘float’
I expect the conditional operator to implicitly convert b
to the type of a-0.5
, float. But this does not happen. How do I achieve this implicit cast?
Ideally, I want to avoid a static cast or an accessor method like float MyFloat::getValue()
.
Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.
The problem is that there are two conversions. The compiler can convert a-0.5
to MyFloat
or it can convert b
to float
. As long as you have both conversions and neither is marked explicit
you'll get this kind of ambiguity all the time.
Only some conversions are done for you. From http://msdn.microsoft.com/en-us/library/e4213hs1(v=vs.71).aspx
The first operand must be of integral or pointer type. The following rules apply to the second and third expressions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With