Let's say we have a class with a function template.
Header file Sort.hpp with the class definition:
#ifndef TEST_SORT_HPP
#define TEST_SORT_HPP
#include <vector>
using namespace std;
class Sort {
public:
template <typename T>
static void mergeSort(vector<T>& arr);
};
#endif //TEST_SORT_HPP
Source file Sort.cpp with the function implementation:
#include "Sort.hpp"
template <typename T>
void Sort::mergeSort(vector<T> &arr) {
// the implementation is irrelevant at the moment
}
This structure would not work for reasons stated in this answer. As also stated in the referenced answer, there are ways to work around this issue, if I do not want to include the implementations straight into the header file.
However, those solutions do not work for me:
If I add
#include "Sort.cpp"
in the end of the header file (before#endif
), I get the error:redefinition of 'static void Sort::mergeSort(std::vector<T>&)'
I do not know in advance all the types the sort is used for and cannot declare them explicitly in the end of the source file.
I also cannot remove
#include "Sort.hpp"
from the Sort.cpp file, because then'Sort' has not been declared
How is this actually done to make it work?
What are the best practices for organizing code into files in case of:
... creating class templates with unknown types (unlimited)?
... creating class templates where it is known which certain types will be used?