为什么这些方法调用会产生歧义?

4
#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
}

请问有人能解释一下为什么这些方法调用是模棱两可的吗?

当它们在“Writeonly”或“Readonly”中组合在一起时,它们不会产生歧义。

我想将其用于基于模板的访问器属性。因此,我希望能够使用“Writeonly”,“Readonly”和“Unrestricted”的实例。

2个回答

6
因为编译器在两个不同的作用域中找到了该名称。
关键是将这两个名称都带入“Unrestricted”的作用域中:
class Unrestricted : public Readonly, public Writeonly {
  public:
  using Readonly::method;
  using Writeonly::method;
};

0

你可能认为它能够工作是因为你在考虑函数重载。问题在于不同的函数位于不同的作用域中。在这种情况下,编译器没有一个重载函数列表来选择正确的函数。

如果你想让它工作,你必须将这些函数放在同一个作用域中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接