I need a helper class with functions which are useful everywhere in my program. Ideally, I wanted a file with a single namespace like below which I can include anywhere in my program:
namespace myhelpers{
int func(){
//function with implementation in one file.
}
}
This doesn't work because I can't have multiple definitions of the function, so I separated into .h and .cpp and still get errors. Code below:
myhelpers.h
#ifndef MYHELPERS
#define MYHELPERS
#include <vector>
class myhelpers {
public:
template <class M>
static std::vector<M> func1(double i);
};
#endif
myhelpers.cpp
#include "myhelpers.h"
template<class M> // <--making this function a non-template function fixes the error.
std::vector<M> myhelpers::func1(double i ) {
return std::vector<double>(5);
};
main.cpp
#include "someclass.h"
int main() {
// also want to use my helpers here.
}
someclass.cpp
#include "myhelpers.h"
#include "someclass.h"
int someclass::func(int i) {
myhelpers::func1<double>(10.0);
return 1;
}
someclass.h
class someclass {
int func(int i);
};
I get this linker error:
Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "public: static class std::vector<double,class std::allocator > __cdecl myhelpers::func1(double)" (??$func1@N@myhelpers@@SA?AV?$vector@NV?$allocator@N@std@@@std@@N@Z) referenced in function "private: int __thiscall someclass::func(int)" (?func@someclass@@AAEHH@Z) directory/someclass.obj 1
If I remove the template from the myhelpers function this linker error disappears, I don't see how this template function changes fixes the error, but I need the templates in my helper functions. I've spent hours looking online for the best way to have a helper class like this but can't find a good answer.
Thanks.