Search code examples
c++templatesincludeheader-files

Is it safe to separate your templated class' declaration and definitions on different header files?


I'm trying to create a library for a school work, and I've been wondering if it is safe to declare a templated class on the main header file containing the class definition and method declarations, but then separating the method definitions in a different header file?

Because I have been able to do this in my example below, but I don't know if it will cause me some problems in the long run.


main program

// main.cpp
#include <iostream>
#include "declaration.hpp"

int main()
{
    card<int> a(5);
    std::cout<<a.getID()<<'\n';
    return 0;
}

main header file

in this header file, only the class definition and the declaration of the method getID() is written but not it's definition, and by the end of the class I included the other header file that contains the method definitions.

// declaration.hpp
#ifndef DEC_HPP
#define DEC_HPP

#include <iostream>

template<typename T>
class card
{
    public:

    T id;
    
    card(const int id) : id(id) {}
    
    T getID();
};

#include "definition.hpp"

#endif

method definitions

This header file contains the method definition of getID() from the main header.

I also included the "declaration.hpp" in this header, and this is the part where I'm not so sure of, because I included both files together with each other.

// definitions.hpp
#ifndef DEF_HPP
#define DEF_HPP

#include <iostream>
#include "declaration.hpp"

template<typename T>
T card<T>::getID()
{
    return id;
}


#endif

I have compiled this program and it's working on my machine, but I just wanted to know if this way of isolating my code will cause me some errors in the future, I don't want to put my templated class definitions in a cpp files because I find it hard to maintain.


Solution

  • This is indeed a better approach because it makes your code look simple and better. Moreover, it is the main reason why header file is used. Your main header file will simply tell that what functions/classes are you using and without even viewing your code, anyone can guess if you are working correctly or not. There wont be any safety issues at all.