Compile-Time Errors at Link-Time

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.』


第二階段是templae被使用時。此階段編譯器能夠檢查的仍然不多。面對一個function template呼叫動作,很多編譯器只檢查引數的個數和型別是否適當。編譯器可以偵測出引數數量太多或不足,也可以偵測出兩個「型別應該相同」的引數是否的確如此。面對class template,編譯器可以檢查用戶是否提供正確數量的template引數,除此之外幾乎沒有其他檢查。







發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *