Ста*_*ько 1 c++ inheritance static-methods
我有以下代码:
struct CommonVariables
{/*some common variables that need to be proceed*/};
struct CommonHandler
{
    static void foo(const CommonVariables& vars) {/*processed vars*/}
    void bar(const CommonVariables& vars) {/*processed vars*/}
};
struct AnotherVariables
{/*another variables*/};
struct AnotherHandler
{
    static void foo(const AnotherVariables& vars) {/*processed vars*/}
    void bar(const AnotherVariables& vars) {/*processed vars*/}
};
struct Derived : CommonHandler, AnotherHandler
{};
当我尝试调用 Derived::foo(/ any variable type /) 或 Derived d; d.bar(/ any variable type /),编译器给我一个错误:“对'foo(or bar)'的引用不明确”。
然而在下面我有几乎相同的情况:
struct DifferentHandler
{
static void foo(const CommonVariables& vars) {}
static void foo(const AnotherVariables& vars) {}
void bar(const AnotherVariables& vars) {}
void bar(const CommonVariables& vars) {}
};
并调用 DifferentHandler::foo(/ any variable type /) 或 'bar' 工作得很好。
有很多解决方案可以解决第一个代码块(模板特性等)。我特别想要的是通过继承重载方法。而且我不明白为什么来自 Derived 的调用是不明确的(因为输入参数有不同的类型,从编译器的角度来看这些函数是不同的。就像在 DifferentHandler 中一样)
注意:我在 VS2015 中尝试过 MinGW5.8(在 Qt Creator 中)和 MSVC2015。两个编译器都生成了相同的错误。
干得好:
struct Derived : CommonHandler, AnotherHandler
{
    using CommonHandler::foo;
    using CommonHandler::bar;
    using AnotherHandler::foo;
    using AnotherHandler::bar;
};
解决您的问题。
原始代码不起作用的原因在 C++ 标准中找到。以下是有趣的引述:
在 10/2:
基类成员被认为是由派生类继承的。继承成员可以以与派生类的其他成员相同的方式在表达式中引用,除非它们的名称是隐藏的或不明确的 (10.2)。
继续阅读 10.2:
成员名称查找确定类范围 (3.3.7) 中名称(id 表达式)的含义。名称查找可能会导致歧义,在这种情况下,程序格式错误....
...由两个组件集组成:声明集,一组名为f...
如果明确找到重载函数的名称,则重载解析(13.3)也会在访问控制之前发生
基本上,它首先按名称进行,然后再应用解析。通过using声明将它们引入派生类将它们全部置于派生类的范围内,在那里正常解析规则开始生效。