简体   繁体   English

C ++:从模板参数继承

[英]C++: Inheritance from template parameter

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 如果我将继承更改为非模板,如下所示: struct C : public A

then it prints "1" and not 0. 然后它打印“1”而不是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 . f()f是一个非独立的名称,因此名称查找发生在模板定义时(在T已知之前)并将其绑定到::f If you want it to call the member function f, then use this to make it a dependent name: 如果你想让它调用成员函数f,那么使用this来使它成为一个从属名称:

template<class T>
struct C : public T {
    C() {
        cout << this->f() << endl;
    } 
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM