C++ Primer 4/e在Template Definitions这个地方有一个关键概念:‘In general, when compiling a template, there are three stages during which the compiler might flag an error: The first is when we compile the template definition itself. The compiler generally can’t find many errors at this stage. Syntax errors, such as forgetting a semicolon or misspelling a variable name, can be detected.
The second error-detection time is when the compiler sees a use of the template. At this stage, there is still not much the compiler can check. For a call to a function template, many compilers check only that the number and types of the arguments are appropriate. The compiler can detect that there are too many or too few arguments. It can also detect whether two arguments that are supposed to have the same type do so. For a class template, the compiler can check that the right number of template arguments are provided but not much else.
The third time when errors are generated is during instantiation. It is only then that type-related errors can be found. Depending on how the compiler manages instantiation, which we’ll cover on page 643, these errors may be reported at link time.
It is important to realize that when we compile a template definition, we do not know much about how valid the program is. Similarly, we may obtain compiler errors even after we have successfully compiled each file that uses the template. It is not uncommon to detect errors only during instantiation, which may happen at link-time.’
中文版的这样写:‘一般而言编译template时,编译器有可能在三个阶段找到错误。第一是编译template定义式时。此阶段通常找不到太多错误。忘记分号或拼错名称等语法错误很容易被侦测出来。
第二阶段是templae被使用时。此阶段编译器能够检查的仍然不多。面对一个function template呼叫动作,很多编译器只检查引数的个数和型别是否适当。编译器可以侦测出引数数量太多或不足,也可以侦测出两个“型别应该相同”的引数是否的确如此。面对class template,编译器可以检查用户是否提供正确数量的template引数,除此之外几乎没有其他检查。
第三阶段是具现化(instantiation)时。只有此时编译器才有可能找出型别相关错误。这种错误有可能在连结期才回报–取决于编译器管理具现化的方式(将于p.643讨论)。
编译一个template定义式时,编译器并不知道程式的合法程度为何。这一点很重要。甚至可能在成功编译了template的每一份用户码之后还获得编译错误。的确,具现化时才侦测出错误并不罕见,而这有可能发生于连结期(link-time)。’
如果发生在连结期的话我想我自己有可能很难了解错误在哪了。