[导入]模板编译模型

1.包含编译模型(inclusion compilation model). 函数声明放在头文件中,定义放在源文件中。头文件尾包含源文件。据说会出现一个模板实例化多次从而导致编译时性能显著降低。

//template.cpp
template<typename T>
void print(const T &v)
{
    cout << "T = " << v <<endl;
}

//template.h
#ifndef TEMPLATE_H
#define TEMPLATE_H

template<typename T>
void print(const T &v);

#include "template.cpp" 

#endif

//main.cpp
#include<iostream>
#include "template.h"  
//#include"template.cpp" 用这条命令代替也可以。

using namespace std;

int main()
{
   
print(1); //ok
    return 0;
}

2. 分别编译模型(seperate compilation model).函数声明和类定义放在头文件中,带export关键字的函数定义和类声明放在源文件中。源文件尾包含头文件。(不知道理解的对不对,用的编译器不支持分别编译,暂时无从判断了

//the template definition goes in a separately-compiled source file

export template<typename T>

T print(const T&v) /*...*/

//class template header goes in shared header file

template <class T> class cl{...};

//cl.cpp implementation file declares cl as exported

export template <class T> class cl;

#include "cl.h"

//cl member definitions


文章来源:http://liyuxia-life.spaces.live.com/Blog/cns!DA1B364675ACF35!265.entry



幸运草 2009-03-24 15:50 发表评论
posted @ 2009-03-24 15:50  liyuxia713  阅读(144)  评论(0编辑  收藏  举报