最近我正在研究著名的“两阶段名称查找”对模板类中名称的确切含义。尽管我已经阅读了很多关于这方面的文章,但我仍然无法了解这方面的一切。现在我对下面显示的代码感到困惑:
template<typename T>
class A
{
public:
void f(T, T){};
};
namespace ns
{
typedef int TT;
void f(int, int){};
};
template<typename T>
class B : public A<T>
{
public:
void g()
{
//f(T(), T()); // it's fine for error here
typedef ns::TT TTT;
f(TTT(), T()); // why this issued an error?
f(ns::TT(), T()); // and this?
}
};
/* I also think it's OK to move ns here */
// namespace ns
// {
// typedef int TT;
// void f(int, int){};
//};
int main()
{
B<int> b;
b.g();
}
请注意第二条评论。由于“f”是一个依赖名称,它的查找应该延迟到“main”函数中的实例化。那时,编译器应该在主函数的范围内执行参数依赖名称查找。我认为现在它应该发现命名空间 ns 中的函数,但它仍然发出编译错误:
1.cpp: In instantiation of 'void B<T>::g() [with T = int]':
1.cpp:30:6: required from here
1.cpp:23:15: error: 'f' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive] f(TTT(), T()); //why this issued an error?
^
1.cpp:23:15: note: declarations in dependent base 'A<int>' are not found by unqualified lookup
1.cpp:23:15: note: use 'this->f' instead
有人可以向我解释一下吗?谢谢。