前言
在 C/C++ 項目里面,何時出現了一個 .inc 文件,第一次看到這個文件時,我感覺很懵逼,於是在好奇心的驅使下,終於在百度上找到了我想要的答案。
.h 和 .inc 文件的區別
// C/C++的標准慣例是將class、function的聲明信息寫在.h文件中。.c文件寫class實現、function實現、變量定義等等。
// 然而對於template來說,它既不是class也不是function,而是可以生成一組class或function的東西。編譯器(compiler)為了給template生成代碼,
// 他需要看到聲明(declaration )和定義(definition ),因此他們必須不被包含在.h里面。
// 為了使聲明、定義分隔開,定義寫在自己文件內部,即.inc文件,然后在.h文件的末尾包含進來。當然除了.inc的形式,還可能有許多其他的寫法.inc, .imp, .impl, .tpp, etc.
// 在編譯器預處理階段會將 .h,.inc 文件內容合並到 .i 文件中,雖然我們在寫代碼時將模板代碼分開了,但是在編譯器預處理階段又被合並,所以這是合理的.
例子
template_statement.h
/**
\copyright Copyright (c) 2020-2022 chongqingBoshikang Corporation
\contact https://www.cnblogs.com/shHome/
\version 0.0.0
\file template_statement.h
\brief 模板類聲明頭文件
\details 這個文件負責聲明模板類的聲明部分,這個模板類是一個非常基礎的類信息類,它只是一個測試類,不用在意那么多
細節
\include
\author sun
\date 2020/12/6
\namespace nothing
\attention 注意事項
\par 修改日志
<table>
<tr><th>Date <th>Version <th>Author <th>Description
<tr><td>2020/12/6 <td>1.0 <td>sun <td>Create initial version
</table>
*/
/**
\brief The header file precompiles the macro to prevent repeated inclusion.
Refer to document name for specific definition form.
\eg _<ProjectName>_<ModuleNmae>_<FileName>_H_.
*/
#ifndef _TEMPLATE_STATEMENT_H_
#define _TEMPLATE_STATEMENT_H_
namespace utils {
template<typename InputType>
class basicClassIdentify
{
public:
/**
\fn 獲取類實體的身份標識碼
\author sun
\date 2020/12/6
\retval InputType
*/
virtual InputType classClassIdentify() const;
protected:
/**
\fn 設置實體的身份標識碼
\details 這個方法應該是受保護的,這個接口理論上不會面向外部
\param 身份標識碼
\author sun
\date 2020/12/6
\see InputType
*/
virtual void setClassIdentify(const InputType& );
protected:
InputType m_classIdentify;
};
/**
編譯器預處理到該行時,會將 template_statement.inc 內的代碼鏈接並生成 .i 預處理文件
*/
#include "template_statement.inc"
} // namespace utils
#endif // !_TEMPLATE_STATEMENT_H_
template_statement.inc
#include "template_statement.h"
template<typename InputType>
InputType basicClassIdentify<InputType>::classClassIdentify() const
{
return this->m_classIdentify;
}
template<typename InputType>
void basicClassIdentify<InputType>::setClassIdentify(const InputType& id)
{
this->m_classIdentify = id;
}
main.cpp
#include "template_statement.h"
#include <stdio.h>
class testting
: public utils::basicClassIdentify<int>
{
public:
testting(const int& id)
: utils::basicClassIdentify<int>()
{
this->setClassIdentify(id);
}
};
int main()
{
testting a(10);
printf("class identify is %d\n", a.classClassIdentify());
return 0;
}