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

Finding names in templatized base classes in C++

我正在阅读 Effective C++ 第三版,第 43 项 "Know how to access names in templatized base classes"。

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;
}

对于上面的代码,我知道如果在D::Foo()中的i之前没有添加B<T>::,编译器会报错“i was not declared in this scope ”。 (但它没有抱怨 iB 中是私有的。)

但是,如果T i;没有在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;
}

编译器默认不在模板化库中查找名称 类。 但为什么我告诉他们他们还是不做?

But why they still don't do even I told them?

因为没有使用成员函数Foo,所以根本就不是instantiated

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.

如果调用 Foo,您可能会得到一个 error,例如

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

顺便说一句

But it didn't complain i is private in B.

因为可访问性检查是在名称查找之后执行的。找不到名称 i,则无法检查任何内容的可访问性。