当两个超类具有相同名称但具有不同签名的成员函数时,这是不明确的 [英] Ambiguous when two superclasses have a member function with the same name, but different signatures
问题描述
struct A {
void f(int x) {}
};
struct B {
template<typename T> void f(T x) {}
};
struct C : public A, public B {};
struct D {
void f(int x){}
template<typename T> void f(T x) {}
};
int main(int argc, char **argv) {
C c;
c.f<int>(3);
D d;
d.f<int>(3);
}
调用 df
很好,但
cf
给出
error: request for member ‘f’ is ambiguous
error: candidates are: template<class T> void B::f(T)
error: void A::f(int)
推荐答案
第一部分是由于成员名称查找,这就是为什么它失败。
The first part is due to member name lookup, that's why it fails.
我会引荐您: 10.2 / 2会员名称查询
以下步骤定义类范围中名称查找的结果
C.首先,类中的每个名称的声明以及
考虑其基类子对象。在一个
子对象B中的成员名f隐藏了子对象A中的成员名f,如果A是B的基本
类子对象。这样隐藏的任何声明都是
从考虑中消除。通过使用声明引入的
的每个声明被认为是来自C的每个
子对象,其是包含由使用声明指定的声明
的类型。
The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub-object B hides a member name f in a sub-object A if A is a base class sub-object of B. Any declarations that are so hidden are eliminated from consideration. Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declaration designated by the using-declaration.
如果生成的声明集不是来自
的同一类型的子对象,或者该集合具有非静态成员,
来自distinct子对象,有一个歧义,程序是
ill-formed 。否则该集合是查找结果。
If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed. Otherwise that set is the result of the lookup.
现在,对于模板函数。
根据 13.3.1 / 7候选函数和参数列表
在候选者是功能模板的每种情况下,使用模板
参数推导(14.8.3,14.8.2)生成候选
功能模板特化。然后,这些候选人以常规方式作为候选函数处理
。给定的名称可以引用一个
或更多的函数模板,也可以引用一组重载的
非模板函数。在这种情况下,从每个函数模板生成的候选函数
与
非模板候选函数集合。
In each case where a candidate is a function template, candidate function template specializations are generated using template argument deduction (14.8.3, 14.8.2). Those candidates are then handled as candidate functions in the usual way. A given name can refer to one or more function templates and also to a set of overloaded non-template functions. In such a case, the candidate functions generated from each function template are combined with the set of non-template candidate functions.
如果您继续阅读 13.3.3 / 1最佳可行功能
是更好的函数,如果:
F1是非模板函数,F2是函数模板
specialization
F1 is a non-template function and F2 is a function template specialization
这就是为什么以下代码段编译并运行非模板函数时没有错误:
That's why the following snippet compiles and runs the non-template function without error:
D c;
c.f(1);
这篇关于当两个超类具有相同名称但具有不同签名的成员函数时,这是不明确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!