模板基类成员如何在继承类中访问

如题,最近在C++标准库的学习过程中,产生了这样的疑问。标准库中解决这个问题一共有3种方式:

  1. 用using来指明该成员为依赖名称(dependent name
  2. 直接把带模板参数的基类作用于成员名称前
  3. 采用this指针来指明该名称依赖于实例化后的类

这3种方式实际上都是在告知编译器,该成员是一个依赖名称,需要在实例化后才能找到。

但是为什么呢?找寻了很久才发现了满意的答案。

Short answer: in order to make x a dependent name, so that lookup is deferred until the template parameter is known.

Long answer: when a compiler sees a template, it is supposed to perform certain checks immediately, without seeing the template parameter. Others are deferred until the parameter is known. It’s called two-phase compilation, and MSVC doesn’t do it but it’s required by the standard and implemented by the other major compilers. If you like, the compiler must compile the template as soon as it sees it (to some kind of internal parse tree representation), and defer compiling the instantiation until later.

The checks that are performed on the template itself, rather than on particular instantiations of it, require that the compiler be able to resolve the grammar of the code in the template.

参考

  1. stack overflow: Why do I have to access template base class members through the this pointer?

  2. dependent name