Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate .h and .cpp files in template class implementation

Tags:

c++

templates

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?

like image 960
Soumyajit Roy Avatar asked Mar 22 '13 18:03

Soumyajit Roy


2 Answers

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?

like image 69
LihO Avatar answered Sep 28 '22 07:09

LihO


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.

like image 32
Angew is no longer proud of SO Avatar answered Sep 28 '22 09:09

Angew is no longer proud of SO