Diamond of death and Scope resolution operator (c++)

后端 未结 3 531
遇见更好的自我
遇见更好的自我 2021-01-11 10:55

I have this code (diamond problem):

#include 
using namespace std;

struct Top
{
    void print() { cout << \"Top::print()\" << e         


        
3条回答
  •  青春惊慌失措
    2021-01-11 11:54

    Why is it ambiguous? I explicitly specified that I want Top from Right and not from Left.

    That was your intent, but that's not what actually happens. Right::Top::print() explicitly names the member function that you want to call, which is &Top::print. But it does not specify on which subobject of b we are calling that member function on. Your code is equivalent conceptually to:

    auto print = &Bottom::Right::Top::print;  // ok
    (b.*print)();                             // error
    

    The part that selects print is unambiguous. It's the implicit conversion from b to Top that's ambiguous. You'd have to explicitly disambiguate which direction you're going in, by doing something like:

    static_cast(b).Top::print();
    

提交回复
热议问题