Implicit conversion insists on using private function

Viewed 48

I have a class that has a conversion operator to int& that I want to hide. I created a derived class that only offers a conversion to int and made the conversion to int& private. But I still cannot make the int conversion to be used, either the compiler tells me that the conversion is ambiguous, or insists to use the int& conversion and tells me it is inaccessible. How do I make this work?

struct Base {
    int value;
    operator int&() { return value; }
};

struct Derived : Base {
    operator int() { return operator int&(); }

   private:
    using Base::operator int&;
};

int main() {
    int p = Derived();
}

P.S. The compiler uses gcc 9.3.0, and the real case is the wrapping of XmlRpc::XmlRpcValue class from ROS to handle probable conversion from double XmlRpcValue type to int or int XmlRpcValue type to double.

1 Answers

I could not find a way through inheritance. But if containment is an option (Derived has a Base instead of is a), it is much simpler:

struct Base {
    int value;
    operator int&() { return value; }
};

struct Derived{
    Base b;
    operator int() { return b.operator int&(); }

};

int main() {
    int p = Derived();
}

The main drawback is that you will have to use explicit delegation for the methods/members you want to offer in Derived

Related