简体   繁体   中英

Nested implicit conversion in C++

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM