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

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

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 @ 2023-07-03 23:56  TechNomad  阅读(45)  评论(0)    收藏  举报