简体   繁体   English

在C ++中的模板化基类中查找名称

[英]Finding names in templatized base classes in C++

I'm reading Effective C++ 3rd Edition, item 43 "Know how to access names in templatized base classes". 我正在阅读有效的C ++ 3rd Edition,项目43“知道如何访问模板化基类中的名称”。

template<typename T>
class B {
    T i;
};

template<typename T>
class D: public B<T> {
public:
    void Foo() {
        T a = B<T>::i;
    }
};

int main() {
    D<int> d;
}

For the above codes, I know if the B<T>:: is not added before i in D::Foo() , compilers will complain " i was not declared in this scope". 对于以上代码,我知道是否在D::Foo() i之前未添加B<T>:: ,编译器会抱怨“未在此范围内声明i ”。 (But it didn't complain i is private in B .) (但是它并没有抱怨iB是私人的。)

However, if T i; 但是,如果T i; is not declared in B, like the following, the compiling goes well. 没有在B中声明,如下所示,编译进行顺利。

template<typename T>
class B {
};

template<typename T>
class D: public B<T> {
public:
    void Foo() {
        T a = B<T>::i;
    }
};

int main() {
    D<int> d;
}

Compilers are defaulted not to find names in templatized base classes. 默认情况下,编译器不在模板化的基类中找到名称。 But why they still don't do even I told them? 但是,为什么我甚至告诉他们,他们仍然不这样做?

But why they still don't do even I told them? 但是,为什么我甚至告诉他们,他们仍然不这样做?

Because the member function Foo is not used, then it's not instantiated at all. 因为没有使用成员函数Foo ,所以根本不会实例化它。

This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition. 这适用于类模板的成员:除非在程序中使用了该成员,否则不会实例化该成员,并且不需要定义。

You might get an error if Foo is called, like 如果调用Foo可能会出错 ,例如

D<int> d;
d.Foo();

BTW BTW

But it didn't complain i is private in B . 但这并没有抱怨iB是私人的。

Because accessibility check is performed after name lookup. 因为在名称查找之后执行了可访问性检查。 The name i is not found, then accessibility of nothing could be checked. 没有找到i的名字,则无法检查任何内容的可访问性。

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

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