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

中文版的這樣寫:『一般而言編譯template時,編譯器有可能在三個階段找到錯誤。第一是編譯template定義式時。此階段通常找不到太多錯誤。忘記分號或拼錯名稱等語法錯誤很容易被偵測出來。

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

第三階段是具現化(instantiation)時。只有此時編譯器才有可能找出型別相關錯誤。這種錯誤有可能在連結期才回報–取決於編譯器管理具現化的方式(將於p.643討論)。

編譯一個template定義式時,編譯器並不知道程式的合法程度為何。這一點很重要。甚至可能在成功編譯了template的每一份用戶碼之後還獲得編譯錯誤。的確,具現化時才偵測出錯誤並不罕見,而這有可能發生於連結期(link-time)。』

如果發生在連結期的話我想我自己有可能很難了解錯誤在哪了。

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

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