为什么这些方法调用不明确?
Why are these method calls 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
}
任何人都可以向我解释为什么这些方法调用不明确吗?
放在一起放在 "Writeonly" 或 "Readonly" 中都没有歧义。
我想将其用于基于模板的访问器属性。因此我希望能够使用 "Writeonly"、"Readonly" 和 "Unrestricted".
的实例
因为编译器在两个不同的范围内找到了名称。
诀窍是将两个名称都纳入 Unrestricted
的范围:
class Unrestricted : public Readonly, public Writeonly {
public:
using Readonly::method;
using Writeonly::method;
};
可能您认为它有效是因为您正在考虑函数重载。问题是不同的功能在不同的范围内。在这种情况下,编译器没有重载函数列表来选择正确的函数。
如果你想让它工作,你必须把函数放在同一个范围内。
#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".
的实例因为编译器在两个不同的范围内找到了名称。
诀窍是将两个名称都纳入 Unrestricted
的范围:
class Unrestricted : public Readonly, public Writeonly {
public:
using Readonly::method;
using Writeonly::method;
};
可能您认为它有效是因为您正在考虑函数重载。问题是不同的功能在不同的范围内。在这种情况下,编译器没有重载函数列表来选择正确的函数。
如果你想让它工作,你必须把函数放在同一个范围内。