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().
..., etc. Adding afloat MyFloat::getValue() constwould not make your interface any worse than it already is: it's adding a way for someone to get a float by saying exactly what they're doing, when you already gave the ability to get a float without even meaning to. - aschepler