IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]C++ 在.h文件中声明,在.cpp文件中定义 模板函数和模板类

    bendanban发表于 2016-05-05 12:39:46
    love 0

    C++ 需要模板函数的定义和声明要放在一起,这样才能根据调用需要选择编译具体的实例。如果我们需要多种实例,每个实例要编译一次,就需要编译多次。在模板函数实现妥当以后,当我们在其它文件中使用某些模板函数的时候,基本所有实例都会被重新编译。如果每次编译时间过长,势必会停滞我们的思维,拖长开发进度。所以在模板函数实现妥当以后,我们希望他只编译一次,在非当前模块被修改时,他也不会被重新编译。这篇博客就是介绍一种简单的方法来实现这个要求。

    具体方法是:显示声明某些实例。


    源代码

    // test.h
    #ifndef __TEST_H__
    #define __TEST_H__
    //////////////////////////////////////////////////////////////////////////
    // template function
    template<class T>
    T func(T,T B = T(0));
    
    //////////////////////////////////////////////////////////////////////////
    // template class
    template<class T>
    class Test
    {
    public:
        Test(){}
        // template member function which is defined in test.cpp
        Test(T a);
        ~Test(){}
    public:
        // template member variables
        T _a;
    };
    #endif
    

    // test.cpp
    #include "test.h"
    //////////////////////////////////////////////////////////////////////////
    // define template function
    template<class T>
    T func(T A, T B){
        return A+B;
    }
    // explicitly declare 
    #define _EXPLICIT_DEFINE(CT) template CT func(CT,CT)
    _EXPLICIT_DEFINE(char);
    _EXPLICIT_DEFINE(int);
    _EXPLICIT_DEFINE(float);
    _EXPLICIT_DEFINE(double);
    #undef _EXPLICIT_DEFINE
    
    //////////////////////////////////////////////////////////////////////////
    // template member function
    template<class T>
    Test<T>::Test(T a){
        this->_a = a;
    }
    // explicitly declare 
    #define _EXPLICIT_DEFINE(CT) template class Test<CT>
    _EXPLICIT_DEFINE(char); 
    _EXPLICIT_DEFINE(int);
    _EXPLICIT_DEFINE(float);
    _EXPLICIT_DEFINE(double);
    #undef _EXPLICIT_DEFINE
    // main.cpp
    #include "test.h"
    #include <iostream>
    using namespace std;
    int main(int argc, char** argv){
        // test template function
        cout << func(10) << endl;
        cout << func(10,1) << endl;
        cout << func(10.) << endl;
        cout << func(10., 1.) << endl;
    
        // test template class
        Test<int> a(13);
        Test<double> b(14);
        cout << a._a << endl;
        cout << b._a << endl;
        return EXIT_SUCCESS;
    }

    运行结果

    在编译之后,执行结果如下:

    这里写图片描述



沪ICP备19023445号-2号
友情链接