In the next code example:
#include <iostream>
using namespace std;
int f() {
return 0;
}
struct A {
int f() {
return 1; }
};
template<class T>
struct C : public T {
C() {
cout << f() << endl;
} };
int main() {
C<A> c; // prints 0
return 0;
}
If I change the inheritance to be non-template like this: struct C : public A
then it prints "1" and not 0.
Why is that?
in f()
, f
is a nondependent name, so name lookup happens at template definition time (before T
is known) and binds it to ::f
. If you want it to call the member function f, then use this
to make it a dependent name:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments