模板元编程之包含模型、显式实例化、分离模型(五)
一、模板的类类型分文件定义
myfirst.h
#pragma once #include <iostream> #include <typeinfo> template <typename T> void print_typeof(T const&);
myfirst.cpp
#include <iostream> #include <typeinfo> #include "myfirst.h" template <typename T> void print_typeof(T const& x) { std::cout << typeid(x).name() << std::endl; }
main.cpp
#include "myfirst.h" int main() { double num = 10.2; print_typeof(num); return 0; }
异常错误:
异常分析:在main.cpp主函数中实例化函数模板类型,并且调用函数模板,由于在main.cpp主函数文件中只包含了模板类的.h文件,因此我们只能实例化.h文件所在的编译单元,又由于模板类的成员函数所在的编译单元未被实例化,因此我们通过函数指针无法找到函数实现体,因为函数实现体压根没有被定义。
二、包含模型
针对上述无法同时实例化.h与.cpp文件内容的问题,可以进行以下修正:
(1).同时包含与模板函数定义有关的.cpp文件与.h文件
#include "myfirst.h" #include "myfirst.cpp" int main() { double num = 10.2; print_typeof(num); return 0; }
(2).将模板的实现文件.cpp包含进模板的声明文件.h中
myfirst.cpp
#include <iostream> #include <typeinfo> template <typename T> void print_typeof(T const& x) { std::cout << typeid(x).name() << std::endl; }
myfirst.h
#pragma once #include <iostream> #include <typeinfo> template <typename T> void print_typeof(T const&); #include "myfirst.cpp"
main.cpp
#include "myfirst.h" int main() { double num = 10.2; print_typeof(num); return 0; }
(3).模板的.h文件和.cpp文件结合在一起组成.h文件
myfirst.h
#pragma once #include <iostream> #include <typeinfo> template <typename T> void print_typeof(T const&); template <typename T> void print_typeof(T const& x) { std::cout << typeid(x).name() << std::endl; }
三、显示实例化
myfirst.h
#pragma once #include <iostream> #include <typeinfo> template <typename T> class Test { public: Test(); ~Test(); private: T data; };
myfirst.cpp
#include "myfirst.h" template class Test<int>; template <typename T> Test<T>::Test():data(0) { std::cout << "构造函数" << std::endl; } template <typename T> Test<T>::~Test() { std::cout << "析构函数" << std::endl; }
main.cpp
#include "myfirst.h" int main() { Test<int> test; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?