模板元编程之包含模型、显式实例化、分离模型(五)

一、模板的类类型分文件定义

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;
}

 

posted @   TechNomad  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示