Sergio Franco
Sergio Franco

Reputation: 98

static_cast on class with conversion operator

I have just come across this behaviour and I am having a hard time understanding why this wouldn't work.

enum class TestEnum
{
 Foo,
 Bar
};

class MyClass
{
public:
    operator TestEnum()
    {
       return m_enum;
    }
    TestEnum m_enum = TestEnum::Foo;
}

MyClass theClass;
int enumValue = static_cast< int >( theClass );  // does not work, conversion operator not called

int enumValue = static_cast< int >( static_cast< TestEnum >( theClass ) ) // works as expected

I understand the compiler only allows 1 implicit conversion and here I think there is only one implicit conversion from MyClass to TestEnum and then an explicit conversion.

Upvotes: 4

Views: 532

Answers (2)

Flaxcode
Flaxcode

Reputation: 1

Static cast operator does not just cast from type to type anyhow there should be a relationship defined between the source and destination type.a relationship can be seen to exist between myclass and testenum type and hence,a conversion operator that defines the relatiomship between the two type is called and also a conversion operator that defines the relationship between integer type and testenum type is called.but there is no direct relationship between my class and int type and hence the compiler can not see any conversion operator that can be used in casting the type and hence the line of code will not work.

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

It is true that one implicit conversion is allowed. However:

static_cast< int >( theClass )

This is a conversion of some non-int class type to int. This is not a conversion to some unspecified type first, and only then a conversion to int. This is one conversion.

Therefore, if there is one implicit conversion to int, then this is allowed. But there isn't a single implicit conversion to int that's available here.

Upvotes: 3

Related Questions