C ++: Inheriting from a template parameter
The following 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 inherit inheritance as non-pattern:
struct C : public A
then it prints "1", not 0.
Why is this?
+3
source to share
1 answer
in f()
, f
is an independent name, so the name is looked up during template definition (before it is T
known) and binds it to ::f
. If you want it to call the member function f, use this
to make it a dependent name:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
+8
source to share