【问题标题】:Why are these method calls ambiguous?为什么这些方法调用模棱两可?
【发布时间】:2016-07-12 10:11:45
【问题描述】:
#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”的实例。

【问题讨论】:

    标签: c++ multiple-inheritance ambiguity member-functions name-lookup


    【解决方案1】:

    因为编译器在两个不同的作用域中找到了名字。

    诀窍是将两个名称都带入Unrestricted的范围内:

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

    【讨论】:

      【解决方案2】:

      您可能认为它有效,因为您正在考虑函数重载。问题是不同的功能在不同的范围内。在这种情况下,编译器没有重载函数列表来选择正确的函数。

      如果你想让它工作,你必须把函数放在同一个范围内。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-06
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 2011-08-01
        • 2023-03-24
        • 2016-03-08
        • 1970-01-01
        相关资源
        最近更新 更多