简体   繁体   English

为什么const / non-const函数的继承过载不明确?

[英]Why is inheritance of a const/non-const function overload ambiguous?

I was trying to create two classes, the first with a non-const implementation of the functions, the second with a const implementation. 我试图创建两个类,第一个使用非const实现的函数,第二个使用const实现。 Here is a small example: 这是一个小例子:

class Base {
protected:
  int some;
};

class A : public virtual Base {
  const int& get() const {
    return some;
  }
};

class B : public virtual Base {
  int& get() {
    return some;
  }
};

class C : public A, B {};

C test;
test.get(); // ambiguous 

The call to the get function is ambiguous. get函数的调用是不明确的。 No matter that the const version needs to match more requirements. 无论const版本需要满足更多要求。 (Calling get on const C is ambiguous as well, but there is one possible function to call.) Is there a reason for such behaviour in the standard? (呼叫get的常量C是模糊的为好,但有一个可能的功能调用。)是否有标准这种行为的理由? Thanks! 谢谢!

Ambiguity occurs when compiler tries to figure out to what entity does the name get refer to, prior to overload resolution. 当编译器试图找出对这个名字有什么实体发生歧义get指,之前重载决议。 It can be a name of function from class A or from class B. In order to build a list of overloads complier needs to select just one of the classes to pull functions from. 它可以是来自类A或类B的函数名。为了构建重载列表,编译器需要只选择其中一个类来从中提取函数。 In order to fix it you can bring that name from both of the base classes into derived class (and make them public): 为了修复它,你可以将这两个基类中的名称带到派生类中(并使它们公开):

class C : public A, public B { public: using A::get; public: using B::get; };

The problem is that you don't actually have one unified overload-set, in which the mutable variant would be unambiguously best, but two distinct overload-sets, in A and B , and the compiler will not automatically merge them. 问题是你实际上没有一个统一的重载集,其中可变变量将是明确最好的,但在ABA 两个不同的重载集,并且编译器不会自动合并它们。

Put

using A::get;
using B::get;

in C to merge the overload-sets and thus resolve the ambiguity. C中合并重载集,从而解决歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM