8

我正在尝试编写一个模板类,它可以根据<class>我通过的方式形成类。问题是我不能在同一个.h文件中声明和定义。在我的项目中,UTF 工具只能处理.cpp文件(用于代码覆盖等)。我在博客中看到他们说“添加.cpp而不是.h”。这是可取的吗?

Template.h

#ifndef TEMPLATE_H_
#define TEMPLATE_H_

template<class T>
class Template
{
public:
    T Add(T a,T b);
};

#endif /* TEMPLATE_H_ */

Template.cpp

#include "Template.h"

template<class T>
T Template<T>::Add(T a, T b)
{
    return a+b;
}

Main.cpp

#include "Template.cpp" //Is this a good practise? 
#include <iostream>

int main(int argc, char **argv) {
    Template<int> obj;
    std::cout<<obj.Add(3,4)<<std::endl;
}

如果这是不可取的,那么我该如何解决这个问题?export?

4

2 回答 2

7

Compiler needs to have an access to the implementation of the methods in order to instantiate the template class, thus the most common practice is either to include the definitions of a template in the header file that declares that template or to define them in header files.

See Why can templates only be implemented in the header file?

于 2013-03-22T18:41:59.073 回答
4

必须在使用它们的每个翻译单元中定义模板。这意味着它们必须在头文件中定义。如果您的工具坚持扩展名.cpp,您也可以提供它,就像您做的那样。

在这种情况下,您甚至不需要将伪标题拆分为.hand 。.cpp你可以把它全部放在那个.cpp里面#include

于 2013-03-22T18:38:39.913 回答