调用基类'函数时必需的类名? [重复]

问题描述 投票:1回答:1

为什么在尝试从同名的Derived类函数调用Base类的模板函数时需要Base类的名称?

考虑以下代码:

struct Base
{
    template < typename >
    void foo() { }
};

struct Derived  : public Base
{
    void foo()
    {
        Base::foo<int>(); // PASSES
        foo<int>(); // FAILS!
    }
    void bar()
    {
        foo<int>(); // Passes if Derived::foo is not there and fails if it is there
    }
};

这是根据标准吗? GCC和clang在这里的行为方式相同。

c++ templates inheritance function-call
1个回答
1
投票

这是名字隐藏。

根据unqualified name lookup的规则,

名称查找检查范围如下所述,直到它找到至少一个任何类型的声明,此时查找停止并且不再检查其他范围。

这意味着,在Derived的成员函数中,将始终找到Derived::foo,然后名称查找停止,Base::foo将不会被考虑。然后你会得到错误,说foo不是模板。

您也可以使用using来解决问题。

struct Derived  : public Base
{
    using Base::foo;
    void foo()
    {
        Base::foo<int>(); // PASSES
        foo<int>(); // PASSES
    }
    void bar()
    {
        foo<int>(); // PASSES
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.