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’ andfloat
      

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


The problem is that there are two transformations. The compiler can convert a-0.5

to MyFloat

or convert b

to float

. As long as you have both transformations and neither of them is checked explicit

, you will get this ambiguity all the time.



+8


source


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


The ternary operator doesn't do any implicit casting if I remember correctly. You will either need to write

static_cast<MyFloat>(a-0.5) 

      

or

static_cast<float>(b). 

      

I will read the C ++ standards document when I get home for more details.

0


source







All Articles