zoukankan      html  css  js  c++  java
  • 【c++ templates读书笔记】【5】模板实战

    1、模板声明和模板定义如果不在同一个文件中,在另一个文件中使用模板时会出现链接错误。

    例子:

    //Myfirst.h
    #ifndef MYFIRST_H
    #define MYFIRST_H
    
    #include<iostream>
    #include<typeinfo>
    using namespace std;
    
    template<typename T>
    void print_typeof(T const& x);
    
    #endif
    
    //Myfirst.cpp
    #include"Myfirst.h"
    #include<iostream>
    #include<typeinfo>
    using namespace std;
    
    template<typename T>
    void print_typof(T const& x){
    	cout << typeid(x).name() << endl;
    }
    
    //main.cpp
    #include"Myfirst.h"
    
    int main(){
    	double ice = 3.0;
    	print_typeof(ice);
    
    	system("pause");
    	return 0;
    }
    

    原因:函数模板print_typeof()的定义还没有被实例化。当实例化一个模板时,编译器必须知道应该实例化哪个定义及要基于哪个模板实参进行实例化。编译器在MyFirst.h文件中看到了模板的声明,但没有模板的定义,这样编译器就不能创建voidprint_typof(double const& x),但这时并不出错,因为编译器认为模板定义在其它文件中,并产生一个指向该定义的引用,让链接器利用该引用解决这个问题。

    2、解决以上问题可以有以下几种方法:

    2.1、包含模型:把模板的定义包含在声明模板的头文件里

    //Myfirst.h
    #ifndef MYFIRST_H
    #define MYFIRST_H
    
    #include<iostream>
    #include<typeinfo>
    using namespace std;
    
    template<typename T>
    void print_typeof(T const& x);
    
    template<typename T>
    void print_typeof(T const& x){
    	cout << typeid(x).name() << endl;
    }
    
    #endif
    //main.cpp
    #include"Myfirst.h"
    
    int main(){
    	double ice = 3.0;
    	print_typeof(ice);
    
    	system("pause");
    	return 0;
    }

    包含模型的缺点:a、增加了头文件的开销 b、大大增加了编译复杂程序所耗费的时间

    2.2、显示实例化

    在1的基础上,添加MyFirstinst.cpp

    //Myfirst.h
    #ifndef MYFIRST_H
    #define MYFIRST_H
    
    template<typename T>
    void print_typeof(T const& x);
    
    #endif
    //Myfirst.cpp
    #include"Myfirst.h"
    #include<iostream>
    #include<typeinfo>
    using namespace std;
    
    template<typename T>
    void print_typeof(T const& x){
    	cout << typeid(x).name() << endl;
    }
    //Myfirstinst.cpp
    #include"Myfirst.cpp"
    
    template void print_typeof<double>(double const& x);
    //main.cpp
    #include"Myfirst.h"
    #include<iostream>
    using namespace std;
    
    int main(){
    	double ice = 3.0;
    	print_typeof(ice);
    
    	system("pause");
    	return 0;
    }

    2.3、分离模型:在模板定义和声明前加上关键字export

    如函数模板声明:

    //Myfirst.h
    #ifndef MYFIRST_H
    #define MYFIRST_H
    
    export template<typename T>
    void print_typeof(T const& x);
    
    #endif

    但VS 2013编译器还不支持。



    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    40岁后学习编程是否太晚了?7点技巧让学习变得轻松有趣
    Java 8五大主要功能为开发者提供了哪些便利?
    如何创建Vim Dotfile?
    程序员:我们为什么爱上直播编程?
    10个最好用的HTML/CSS 工具、插件和资料库
    如何选择PHP框架?
    编程语言五花八门,哪种可以让程序员赚到更多钱?
    安卓项目中使用JSON引发的一个小错误 Multiple dex files define Lorg/apache/commons/collections/Buffer
    (转)获取当前应用的版本号和当前android系统的版本号
    Android访问网络,使用HttpURLConnection还是HttpClient?
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4921344.html
Copyright © 2011-2022 走看看