在下一个代码示例中:
#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;
}
如果我像这样将继承更改为非模板:
struct C : public A
然后它打印“1”而不是 0。
这是为什么?
最佳答案
在 f()
中,f
是一个独立的名称,因此名称查找发生在模板定义时(在 T
已知之前)并且将它绑定(bind)到 ::f
。如果你想让它调用成员函数 f,那么使用 this
使它成为依赖名称:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
关于C++:从模板参数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794082/