C++ 模板显式实例化

// template.hpp
template<typename T>
class Dylan
{
public:
    Dylan(T t);
    T m_data;
};
 
// template.cpp
#include "template.hpp"
template<typename T>
Dylan<T>::Dylan(T t)
{
    m_data = t;
}
 
template class Dylan<int>;        //模板实例化定义
 
// main.cpp
#include "template.hpp"
extern template class Dylan<int>; //模板实例化声明,告诉编译器,此实例化在其他文件中定义
                                  //不需要根据模板定义生成实例化代码  
int main()
{
    Dylan<int> dylan(3);          //OK, 使用在template.cpp中的定义
    Dylan<float> dylan1(3.0);     //error, 引发未定义错误
    return 0;
}

main函数中Dylan<float> dylan1(3.0);没有显式实例化Dylan<float>,编译会报错。




posted @ 2024-11-08 14:01  double64  阅读(51)  评论(0)    收藏  举报