1

Why the Base class' name is required while trying to call the Base class' template function from the Derived class' function of same name?

Consider this code:

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

Is this according to the standard? Both GCC and clang behave the same way here.

Vahagn
  • 4,670
  • 9
  • 43
  • 72

1 Answers1

1

This is name hiding.

According to the rule of unqualified name lookup,

name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

That means, in the member functions of Derived, Derived::foo will always be found and then name lookup stops, Base::foo won't be considered at all. Then you'll get the error which says foo is not a template.

You can also use using to solve the issue.

struct Derived  : public Base
{
    using Base::foo;
    void foo()
    {
        Base::foo<int>(); // PASSES
        foo<int>(); // PASSES
    }
    void bar()
    {
        foo<int>(); // PASSES
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405