C++参数依赖查找(ADL)是否适用于变量与类型名?
C++参数依赖查找(ADL)对变量和类型名的生效问题
核心疑问
C++的参数依赖查找(ADL)是否会在查找变量和类型名时生效?
第一个合法程序
以下程序在g和clang中均可正常编译运行:
template<class T> struct C; template<class T> struct B{ void f(){ cout << "a=" << C<T>::a << endl; } }; template<class T> struct C{static const int a = 1;}; int main() { B<int> b; b.f(); return 0; }
编译器判定C<T>::a属于依赖名,会在模板实例化(即调用b.f()时)才进行查找,因此能找到后续定义的C<T>中的静态成员a。
第二个报错程序
但以下非模板程序会直接编译报错:
#include <iostream> using namespace std; class D; struct E{ void f(){ cout << D::a << endl; // error: incomplete type ‘D’ used in nested name specifier } }; class D{ static const int a = 7; }; int main() { E e; e.f(); return 0; }
报错原因是常规查找在函数定义阶段无法找到D::a的声明,因为此时D还是不完全类型。
困惑点
根据cppreference的说明,ADL仅适用于函数调用表达式,而第一个程序中并没有用到ADL,那编译器是如何在模板实例化时找到C<T>::a的?
内容的提问来源于stack exchange,提问作者ckf104
相关产品推荐
相关产品推荐

