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;
}
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.
See Why can templates only be implemented in the header file?
Templates must be defined in every translation unit in which they are used. This means they must be defined in header files. If your tool insists on the extension .cpp
, you can as well provide it, just like you did.
You don't even need to split the pseudo-header into .h
and .cpp
in this case. You can just put it all in the .cpp
and #include
that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With