3

Consider the following piece of code:

#include <iostream>

void f() {
        std::cout << "1";
}

struct B { 
        void f() { std::cout << "2"; }
};

struct D : B { 
        void g() {
                f();
        }
};

int main() {
        D d;
        d.g();
}

It outputs "2" when compiled with my g++ 11.2.0, c++17 standard. But if I turn these structures into templates like this:

#include <iostream>

void f() {
        std::cout << "1";
}

template<typename>
struct B { 
        void f() { std::cout << "2"; }
};

template<typename T>
struct D : B<T> {
        void g() {
                f();
        }
};

int main() {
        D<int> d;
        d.g();
}

It outputs "1"! Why?

Kolay.Ne
  • 1,345
  • 1
  • 8
  • 23
  • 2
    related https://stackoverflow.com/questions/36095149/calling-method-of-template-base-class, https://stackoverflow.com/questions/19128796/why-can-i-call-base-template-class-method-from-derived-class – 463035818_is_not_an_ai Mar 11 '22 at 09:43
  • 1
    This has to do with the two-phase lookup in templates. Since the base class is dependent on the template parameter, `f` is assumed to be the global `f`. If you use `this->f()` or `B::f()` it will call the member function from the base class. – super Mar 11 '22 at 09:59
  • ... or `D::B::f()` – Ted Lyngmo Mar 11 '22 at 10:02

0 Answers0