[英]C++: Inheritance from template parameter
在下一个代码示例中:
#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
已知之前)并将其绑定到::f
。 如果你想让它调用成员函数f,那么使用this
来使它成为一个从属名称:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.