模板的分类编译

一、模板为什么不能分离编译?

普通函数

template.h:

#pragma once
#include<iostream>
using namespace std;
void Func();

template.cpp:

#include"template.h"
void Func()
{
    cout << "普通函数" << endl;
}

test.cpp:

#include"template.h"
int main()
{
    Func();
    system("pause");
    return 0;
}

运行结果
这里写图片描述

分析:

分离编译后程序正常执行。

模板函数

template.h:

#pragma once
#include<iostream>
using namespace std;
void Func();
template<class T>
void TFunc(const T& a);
template<class T>
class TClass
{
public:
    TClass();
};

template.cpp

#include"template.h"
void Func()
{
    cout << "普通函数" << endl;
}
template<class T>
void TFunc(const T& a)
{
    cout << "模板函数" << endl;
}
template<class T>
TClass<T>::TClass()
{
    cout << "模板类" << endl;
}
//显示实例化
template
void TFunc<int>(const int& a);
template 
void TFunc<double>(const double& a);
template class TClass<int>;

test.cpp

#include"template.cpp"//既有声明也有定义
int main()
{
    Func();
    TFunc(10);
    TFunc(1.111);
    TClass<int> t;
    system("pause");
    return 0;
}

模板函数报错结果:
这里写图片描述

模板类报错结果:
这里写图片描述
模板无法生成对象,只有实例化后才能生成代码。
这里写图片描述

分离后压根就.h文件夹里没有实例化的对象,实例化是在另外一个cpp,两个cpp不会交互,不会实例化出对象,所以模板不能进行 分离编译

二、怎样解决这个问题?

1、进行显示实例化
这里写图片描述
缺陷:只能实例化出一种类型
这里写图片描述

template.cpp中生成一个obj
test.cpp中也生产一个obj
2、最好的方式是把声明和定义放一个头文件里

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值