Implicit conversion in C ++
In C ++, I am 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;
}
This throws a compiler error:
error: operands to ?: have different types ‘MyFloat’ and ‘float’
I expect the conditional operator to implicitly convert b
to type a-0.5
, float. But that doesn't happen. How to achieve this implicit cast?
Ideally, I want to avoid a static act or accessor for example float MyFloat::getValue()
.
+3
source to share
3 answers
Only a few transformations have been done for you. From http://msdn.microsoft.com/en-us/library/e4213hs1(v=vs.71).aspx
The first operand must be of an integer or pointer type. The following rules apply to the second and third expressions:
- If both expressions are of the same type, the result is of that type.
- If both expressions are arithmetic or enumerated types, ordinary arithmetic conversions (in Arithmetic conversions) are performed to convert them to the common type.
- If both expressions are pointer types, or if one is a pointer type and the other is a constant expression that evaluates to 0, a pointer conversion is performed to convert them to a common type.
- If both expressions are reference types, reference conversion is performed to convert them to a common type.
- If both expressions are void, the common type is void.
- If both expressions are of a given class type, the common type is that of that class.
+1
source to share