前言

在 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;
}
posted on 2020-12-06 19:23  怪小子  阅读(5569)  评论(0编辑  收藏  举报