use*_*739 3 c++ inheritance templates struct
在下一个代码示例中:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果我将继承更改为非模板,如下所示:
struct C : public A
然后它打印"1"而不是0.
这是为什么?
in f(),f是一个非依赖名称,因此名称查找发生在模板定义时(之前T已知)并将其绑定到::f.如果你想让它调用成员函数f,那么使用this它来使它成为一个从属名称:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
Run Code Online (Sandbox Code Playgroud)