本文介绍了在模板类实现中分离.h和.cpp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个模板类,可以根据< class> 我传递形成类。问题是我不能在同一个 .h 文件中声明和定义。在我的项目中,UTF工具只能使用 .cpp 文件(代码覆盖率等)。我在博客中看到他们说添加 .cpp 而不是 .h 。这是可取的吗?

I am trying to write a template class that can form classes depending on the <class> I pass. The problem is I cannot declare and define in the same .h file. In my project, the UTF tool can only work with the .cpp files (for code coverage, etc.). I have seen in a blog that they say "Add .cpp instead of .h". Is this advisable?

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

If this is not advisable then how do I solve this issue? export?

推荐答案

编译器需要具有对方法,以便实例化模板类,因此最常见的做法是 在头文件中定义模板

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.

请参阅

这篇关于在模板类实现中分离.h和.cpp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:17