现在的位置: 首页 > 综合 > 正文

关于C++模版的代码文件放置问题

2013年05月31日 ⁄ 综合 ⁄ 共 1370字 ⁄ 字号 评论关闭

方法一:包含编译模型(√)

        在包含编译模型中,编译器必须看到用到的所有模板的定义。一般而言,可以通过在声明函数模板或类模板的头文件中添加一条#include 指示使定义可用,该#include 引入了包含相关定义的源文件:

//header file utilities.h
#ifndef UTILITIES_H      
#define UTILITIES_H
template<typename T>int compare(const T& v1, const T& v2);
#include "utilities.cpp"   //get the definitions for compare etc.
#endif

//implemenatation file utilities.cpp
template<typename T>int compare(const  T& v1, const T& v2)
{
    if (v1 < v2) return -1;
    else if (v2 < v1) return 1;
    else return 0;
}

这一策略使我们能够保持头文件和实现文件的分离,但是需要保证编译器在编译使用模板的代码时能看到两种文件。


方法二:分别编译模型

         在分别编译模型中,编译器会为我们跟踪相关的模板定义。但是我们必须让编译器知道要记住给定的模板定义,可以使用export关键字来做这件事。

          export关键字能够指明给定的定义可能会需要在其他文件中产生实例化。在一个程序中一个模板只能定义为导出一次。编译器在需要产生这些实例化时计算出怎样定位模板定义。export关键字不必在模板声明中出现。

         一般我们在函数模板的定义中指明函数模板为导出的,这是通过在关键字template之前包含export关键字而实现的:

//the template definition goes in a separately-compiled source file
export template<typename Type>
Type sum(const Type& t1,  const  Type& t2)                                                                                          
{                                                                                                                                   
//...                                                                                                                              
}

这个函数模板的声明像通常一样应放在头文件中,声明不必指定export。

         对类模板使用export更复杂一些。通常,雷声明放在头文件中,头文件中的类定义体不应该使用关键字export,如果在头文件中使用export,则头文件只能被程序中的一个源文件使用。  

        相反,应该在类的实现文件中使用export:

//class template header goes in shared header file
template<typename Type>class Queue{....};

//Queue.cpp implementation file declares Queue as exported
export template<typename Type>class Queue;
#include "Queue.h"
//Queue member definitions

     导出类的成员将自动声明为导出的。也可以将类模板的个别成员声明为导出的,在这种情况下,关键字export不在类模板本身指定,而是只在被到处的特定成员定义上指定。导出成员函数的定义不必在使用成员时可见。任意非导出成员的定义必须像在包含模型中一样对待:定义放在定义类模板的头文件中。

           

抱歉!评论已关闭.