模板的分类编译

本文探讨了C++中模板为何不能进行分离编译的问题,并提供了两种解决方案:显示实例化及将声明与定义置于同一头文件内。通过实例展示了这两种方法的具体应用。

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

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

普通函数

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、最好的方式是把声明和定义放一个头文件里

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值