C++中的INL

inl文件介紹

inl文件是內聯函數的源文件。內聯函數一般在C++頭文件中實現,可是當C++頭文件中內聯函數過多的狀況下,咱們想使頭文件看起來簡潔點,能不能像普通函數那樣將內聯函數聲明和函數定義放在頭文件和實現文件中呢?固然答案是確定的,具體作法將是:將內聯函數的具體實現放在inl文件中,而後在該頭文件末尾使用#include引入該inl文件。ios

因爲編譯器等不支持將模板函數、模板類等放單獨分開編譯,可是有了inl文件,咱們能夠把聲明放在頭文件中,而後將具體實現放在inl文件中。c++

對於比較大的工程來講,出於管理方面的考慮,模板函數、模板類的聲明通常放在一個或少數幾個頭文件中,而後將其定義部分放在inl文件中。這樣可讓工程結構清晰、明瞭。git

在Google的C++代碼編程規範中也說到了inl文件,須要閱讀的同窗能夠從這裏閱讀Google的C++代碼規範:Google C++ Style Guidegithub

簡單示例

  1. //inl_demo.h
  2. #ifndef _INL_DEMO_H_
  3. #define _INL_DEMO_H_
  4. template<typename T>
  5. T return_max(T &T1, T &T2);
  6. #include "inl_demo.inl"
  7. #endif
  1. //inl_demo.inl
  2. #ifndef _INL_DEMO_INL_
  3. #define _INL_DEMO_INL_
  4. #include "inl_demo.h"
  5. template<typename T>
  6. T return_max(T &T1, T &T2){
  7. return T1 > T2 ? T1 : T2;
  8. }
  9. #endif
  1. //main.cc
  2. #include <iostream>
  3. #include "inl_demo.h"
  4. using namespace std;
  5. int main(int argc, char *argv[]){
  6. int a = 10;
  7. int b = 20;
  8. cout << "The Max is :" << return_max(a, b) << endl;
  9. return 0;
  10. }
做者: hahaya
出處: http://hahaya.github.com/inline-file-in-cplusplus 本文版權歸做者全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
相關文章
相關標籤/搜索