在VC9.0中实现C++模板类头文件和实现文件分离的方法

本文介绍了三种在C++中实现模板类头文件与实现文件分离的方法,包括使用包含模型、预处理器指令以及直接包含实现文件等技术手段,并通过实验验证了这些方法在Visual C++ 9.0环境下的可行性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何实现C++模板类头文件和实现文件分离,这个问题和编译器有关。

引用<<C++primer(第四版)>>里的观点:1)标准C++为编译模板代码定义了两种模型:“包含”模型和“分别编译”模型。2)所有编译器都支持“包含”模型,某些编译器支持“分别编译”模型。

第一种方法:按C++primer中的“包含”模型,在定义模板类的头文件中的末行用语句:#include "template_compile.cpp"

在类模板头文件template_compile.h中:

#ifndef _TEMPLATE_COMPILE_H
#define _TEMPLATE_COMPILE_H

template<class T> class base;

#include "template_compile.cpp"
#endif

在类模板的实现文件template_compile.cpp中:

 

template<class T>
class base
{
public:
	base() {};
	~base() {};
	T add_base(T x,T y);
};

template<class T>
T base<T>::add_base(T x,T y)
{
	return x+y;
}

在使用模板的测试文件use_template.cpp中:

#include<iostream>
using namespace std;  
#include "template_compile.h"

void main()  
{  
	base<int> bobj;  
	cout<<bobj.add_base(2,3)<<endl;  
}  



第二种方法:bruceteen提出的:使用define

在类模板头文件template_compile.h中:

 

template<class T>
class base
{
public:
  base() {};
  ~base() {};
  T add_base(T x,T y);
};
#define FUCK
#include "template_compile.cpp"

在类模板的实现文件template_compile.cpp中:

#ifdef FUCK
template<class T>
T base<T>::add_base(T x,T y)
{
  return x+y;
}
#endif

测试文件不变。

实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离

方法三:

在类模板头文件template_compile.h中:

 

template<class T>
class base
{
public:
    base() {};
    ~base() {};
    T add_base(T x,T y);
};

在类模板的实现文件template_compile.cpp中:

#include "template_compile.h"
template<class T>
T base<T>::add_base(T x,T y)
{
	return x+y;
}

在使用模板的测试文件use_template.cpp中:使用#include "template_compile.cpp"

 #include<iostream>
#include "template_compile.cpp"
using namespace std;
void main()
{
    base<int> bobj;
    cout<<bobj.add_base(2,3)<<endl;
}

实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离。

另外实验证明:VC9.0不支持“分别编译”模型。

转自:http://blog.youkuaiyun.com/Microsues/article/details/6078385

ps:方法1与原文不同,

参考:http://kymcuc.blog.163.com/blog/static/201942114201231184541184/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值