Is there a way to make a custom cast operator only available (or only implicit) if the object is const?
Example:
class Foo;
class Bar;
class MyClass {
public:
operator Foo() const;
operator Foo() = delete; // this doesn't seem to have any effect
// I also tried explicit operator Foo(); - no change
operator Bar();
};
As you can see, I'd like MyClass to be implicitly cast to Foo if it is const, but to Bar if it is not const. This is because a pair of overloaded functions exists:
void f(Foo x);
void f(Bar x);
And I'd like to be able to pass MyClass to f, so that the correct function is selected depending on whether it is const or not. This way however, I am getting an ambiguous call to overloaded function. Why?
int main() {
f(MyClass());
}
Important: I know that I can make this work easily by turning the cast operators into constructors, but unfortunately, Foo, Bar, and f cannot be modified. For context, this is an idea to solve my other problem: Is there a way to resolve this ambiguous implicit cast operator overload?