AlwaysLearning
AlwaysLearning

Reputation: 8011

Calling template function member of the base when it's called the same name

I am trying to understand why the following code does not compile (using gcc 4.8.2):

struct A {
    template <typename T>
    T f() {return T(0);}
};

struct B : A {
    using MyT = int;
    MyT f() {return (A *)this->template f<MyT>();}
};

int main()
{
    B b;
    std::cout << b.f() << std::endl;
    return 0;
}

If I change the name from f to f1 in the base, then the following compiles just fine:

struct A {
    template <typename T>
    T f1() {return T(0);}
};

struct B : A {
    using MyT = int;
    MyT f() {return this->template f1<MyT>();}
};

Upvotes: 0

Views: 38

Answers (1)

ForEveR
ForEveR

Reputation: 55887

Just because operator precendence, you are casting result of f function to A*, instead of cast this to A* and it's actually better to use static_cast.

MyT f() {return static_cast<A*>(this)->f<MyT>();}

this will work. And also you have name hiding, you just do this:

struct B : A {
    using MyT = int;
    using A::f;
    MyT f() {return this->f<MyT>();}
};

Upvotes: 3

Related Questions