C++ template changes name lookup order?

Viewed 43

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?

0 Answers
Related