內聯關鍵字與模板
考慮使用內聯關鍵字與模板時,會出現一個問題,考慮到編譯器的能夠確定內聯的好處。
答案:不,不是Irrelevant
儘管編譯器了解,內聯關鍵字仍然與模板相關。雖然函數模板預設通常不是內聯的,但它們的明確專業化可以使它們內聯。
特定情況
在某些情況下,省略 inline 關鍵字可能會導致問題。考慮以下範例:
#include "tpl.h"
#include "tpl.h"
#ifndef TPL_H #define TPL_H template<class T> void f(T) {} template<class T> inline T g(T) {} template<> inline void f<>(int) {} // OK: inline template<> int g<>(int) {} // error: not inline #endif
編譯此程式碼會導致多個定義錯誤,因為 g未明確標記為內嵌。
經驗法則
為了保持一致性並避免潛在錯誤,請考慮對打算內聯的函數模板使用 inline 關鍵字。這與 Vandevoorde/Josuttis 的“C 模板:完整指南”中建議的經驗法則一致,該規則建議在真正需要時進行內聯編寫。
以上是您應該在 C 模板中使用'inline”關鍵字嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!