Question

I wanted have implicit conversion in two level. The following code snippet is prototype of the problem I am facing.

//Sources
class A
{
public:
    void print()
    {
        std::cout <<"Class A"<< std::endl;
    }

    operator int()
    {
        return 1;
    }
};

class B
{
public:
    void print()
    {
        std::cout <<"Class B"<< std::endl;
    }

    operator A()
    {
        return A();
    }
};

class C
{
public:
    void print()
    {
        std::cout <<"Class C"<< std::endl;
    }
    operator B()
    {
        return B();
    }
};


void print_(A a)
{
    a.print();
}

//driver

int main( int argc, char* argv[] )
{
    C c;

    //print_( c ); // compilation error
    //print_( C() ); // compilation error   
    print_( c.operator framework::configuration::B() ); //when explicitly invoked it worked 
    return 0;
}

I looked into the example provided in the following links was convinced this is achievable.

How do conversion operators work in C++?

Operator overloading

Was it helpful?

Solution

The standard only allows one implicit conversion involving a user defined type. You have two, hence the compilation error.

See 12.3/4

At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top