在c++里, 模板类在编译的时候,与独立类不同,需要经过两阶段查找,明白两阶段查找,对于解决诡异的编译错误,帮助很大
1. 什么是两阶段查找:
(1) 在模板定义阶段,先对独立的(与模板参数无关的)成员进行检查,检查不通过则编译报错;
(2)在实例化模板时,对非独立的成员进程检查(检查是否在子类或基类中)
举例:
#include <stdio.h>class A{public:void add(){printf("A add\n");}};class B:public A{public:void cal(){add();}};int main(){B b;b.cal();}
不涉及到模板时,编译是不报错的,符合c++语法,当涉及语法时,编译如下:
#include <stdio.h>template<typename T>class A{public:void add(){printf("A add\n");}};template<typename T>class B:public A<T>{public:void cal(){add(); // 此处报错,第一阶段查找时,add()定性为独立,认为它是非成员变量,但又找不到this->add(); // 此处正确,第一阶段认为它是非独立(因为与this有关,即与T有关)
//,第二阶段查找时,B中找不到,则在基类A中能找到}};int main(){B<float> b;b.cal();}
error: there are no arguments to ‘add’ that depend on a template parameter, so a declaration of ‘add’ must be available [-fpermissive]