I'm trying to implement a class in C++ which contains most of the functions which I might need to use across different class hierarchies (the project has multiple different inheritance trees).
After reading through and taking advise from multiple answers for this kind of implementation on Stack overflow, Why can templates only be implemented in the header file? I decided to implement this using a .h file and 2 different .cpp files. I tried to implement a small test case using this FAQ as a guideline. The code is as below:
test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <cmath>
#include <complex>
template<typename T>
class test{
public:
static bool IsClose(const T &a, const T &b);
};
#endif
testImpl.h
#include "test.h"
template <typename T>
bool test<T>::IsClose(const T &a, const T &b){
return (std::abs(a-b) <= (1e-8 + 1e-5 * std::abs(b)));
}
testImpl.cpp
#include "testImpl.h"
template class test<int>;
template class test<double>;
main.cpp
#include "test.h"
#include <iomanip>
int main(){
std::cout << std::boolalpha << test<double>::IsClose(1e-7,1.1e-7) << std::endl;
return 0;
}
On compiling using g++ -o test main.cpp testImpl.cpp
I'm getting the following error:
main.cpp: In function ‘int main()’:
main.cpp:4:36: error: ‘test’ is not a template
std::cout << std::boolalpha << test<double>::IsClose(1e-7,1.1e-7) << std::endl;
If anyone can advise me on where I'm going wrong your help will be much appreciated. Thanks in advance!! Also if there is a better method to achieve what I'm trying to do, your thoughts are welcome on that matter as well.