0

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.

Xephex
  • 33
  • 5
  • You can always make a namespace-scope function `inline` or `static`. – Some programmer dude Jul 28 '20 at 12:22
  • ***Severity Code Description*** Note: the output tab has the error message in a better format than the errors list. Sometimes the message will also be more verbose as the errors list shortens the message at times. – drescherjm Jul 28 '20 at 12:27
  • Ok, so if I make a namespace filled with inline functions, I should be able to include it anywhere in my project ? – Xephex Jul 28 '20 at 12:27
  • It will work however I would question if you want to make them all inline versus implementing the larger functions in a translation unit. – drescherjm Jul 28 '20 at 12:30

0 Answers0