Why are these methods ambiguous?

#include <string>
using String = std::string;

class Base {
protected:
    String value;
};

class Readonly : virtual Base {
public:
    const String& method() const {
        return value;
    }
    String& method() {
        return value;
    }
};

class Writeonly : virtual Base {
public:
    Writeonly& method(const String& value) {
        this->value = value;
        return *this;
    }
    Writeonly& method(String&& value) {
        this->value = std::move(value);
        return *this;
    }
};

class Unrestricted : public Readonly, public Writeonly {};

void usage() {
    String string;
    Unrestricted unrestricted;
    unrestricted.method(string); // ambiguous
    string = unrestricted.method(); // ambiguous
}

Can someone explain to me why these method calls are ambiguous?

They are not ambiguous if combined in "Writeonly" or "Readonly".

I would like to use this for template based access properties. So I want to be able to use instances of "Writeonly", "Readonly" and "Unrestricted".

+4
source share
2 answers

Because the compiler found the name in two different areas.

The trick is to bring both names to the scope Unrestricted:

class Unrestricted : public Readonly, public Writeonly {
  public:
  using Readonly::method;
  using Writeonly::method;
};
+6
source

, , , . , . , .

, , togheter .

0

All Articles