0

I have a C++ using a class specified on separate .hpp/.cpp files. This class has the particularity of having a templated member function that takes a const std::vector as argument, and here is the root of the problem.

myclass.hpp:

class myclass {

    //...
    public: 
        myclass();
        template <typename _t> int myfunction(const std::vector<_t> *values);

    //...
}

myclass.cpp:

#include "myclass.hpp"

//...
template <typename _t> int myclass::myfunction(const std::vector<_t> *values){
    // do stuff
    return 0;
}

and my main.cpp:

#include "myclass.hpp"

int main(int argc, char const *argv[]){

    myclass foo;
    std::vector<int> bar(5,100);
    foo.myfunction(bar);

    return 0; 
}

However, when I try to compile all this with g++ main.cpp myclass.cpp -o main -I /usr/include I get the error:

undefined reference to `int myclass::myfunction<int>(std::vector<int, std::allocator<int> > const*)' 

which is strange since the syntax seems to be correct (and it passes g++ check). The problem is not with how I am building the code or the file setup, since I am able to compile the code if I comment out the templated function.

joaocandre
  • 1,621
  • 4
  • 25
  • 42

1 Answers1

1

Template functions must be placed in headers, not sources. That is because template is basically an instruction for the compiler, that tells him, how to generate code for some set of template parameters. It's not the definition itself. So template "body" must be available when particular specialization is being instantiated.

Straightly speaking, this code:

template <typename _t> int myclass::myfunction(const std::vector<_t> *values){
    // do stuff
    return 0;
}

should be placed in .hpp, not .cpp file.

You may also want to read this SO question: link.

Community
  • 1
  • 1
Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49