gpt4 book ai didi

c++ - 当两个父类(super class)具有同名但签名不同的成员函数时不明确

转载 作者:IT老高 更新时间:2023-10-28 12:51:56 24 4
gpt4 key购买 nike

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);
}

什么原因调用d.f就可以了,但是c.f给了

error: request for member ‘f’ is ambiguous
error: candidates are: template<class T> void B::f(T)
error: void A::f(int)

最佳答案

第一部分是由于成员名称查找,这就是它失败的原因。

我会推荐你​​:10.2/2 成员名称查找

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.

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 候选函数和参数列表

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 被认为是一个更好的函数,如果:

F1 is a non-template function and F2 is a function template specialization

这就是为什么下面的代码片段编译并运行非模板函数没有错误:

D c;
c.f(1);

关于c++ - 当两个父类(super class)具有同名但签名不同的成员函数时不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com