Bob*_*ohn 2 c++ templates compiler-errors template-function
template <typename T>
void list<T>::copyAll(const list &l)
{
if(l.isEmpty()) //if the list-to-copy is empty, we're done
{
first = last = NULL;
}
else
{
node *toFollow = l->yhjfrtydfg;
node *whatever = l.asfqwejfq3fqh23f8hq23r1h23017823r087q1hef;
while(toFollow != NULL)
{
T *newO = new T(*(toFollow->o));
T here = *newO;
insertBack(&here);
toFollow = toFollow->next;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序编译(与程序的其余部分),尽管这两条线node *toFollow = l->yhjfrtydfg;和node *whatever = l.asfqwejfq3fqh23f8hq23r1h23017823r087q1hef;明显的疯狂投入.这很奇怪,因为任何其他错误都被抓住了.有帮助吗?
"依赖名称"(模板中使用的名称,其含义取决于模板参数)仅在模板实例化时解析,而不是在定义模板时解析.如果你没有实例化模板,那么它可以包含你喜欢的任何疯狂的名字,只要它在语法上是正确的.
如果实例化您的程序将无法编译:
list<int> l;
l.copyAll(l); // ERROR
Run Code Online (Sandbox Code Playgroud)
仅在模板实例化后才会解析依赖于模板参数的名称.在任何情况下都只解析非依赖名称.
C++创造了这种"两阶段查找",其中阶段1是首次解析时,阶段2是实例化时间.
例如:
template <typename T>
void frob() {
foo = 5; // non-dependent, name must exist at this point
T bar;
bar.frobnicate = 7; // dependent, name is looked up upon instantiation
bar->is->a.funny(T::hing); // dependent, likewise looked up later
}
Run Code Online (Sandbox Code Playgroud)