这个问题在这里已有答案:
为什么在尝试从同名的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在这里的行为方式相同。
这是名字隐藏。
根据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
}
};