Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined references to member functions of a class template

I want to use iterators in template class method. Here is my code: (testclass.h)

template<typename T, typename container>
class TestClassX
{
public:
    void gen(typename container::iterator first );
};

and file testclass.cpp:

template<typename T, typename container>
void TestClassX<T, container>::gen(typename container::iterator first)
{

}

When i try to run it:

TestClassX<unsigned, std::vector<unsigned> > testx;
testx.gen(it);

I get an error:

Error:undefined reference to `TestClassX<unsigned int, std::vector<unsigned int, std::allocator<unsigned int> > >::gen(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >)'

I use mingw32 4.4

I want to have a class that can write to different containers like std::vector, std::list, QVector or QList all that have STL-style iterators.

like image 769
seb6k Avatar asked Feb 19 '12 19:02

seb6k


1 Answers

Template class methods NEED NOT be defined in the header files. But if you do this you need to define a separate compilation unit (for example templates.cpp) and in that you include the source code file of the template class (eg. #include "container.cpp" // the .cpp NOT the .hpp file) then you need to define the instances of the templates that you are using (eg. template class Container;). You also need to define the object for the template class (eg Link). In this particular case, since we are using a pointer to this object (eg Link*, in Containter ) we merely need to 'forward declare' that object.

Here is the full template.cpp file. Which you would compile and link in with the rest of the code.

class Link;
#include "Container.cpp"    // use the source code, not the header
template class Container<Link*>; 

I like using this method because it prevents the compiler from generating template class instances automagically and lets you know when it can't find it.

Compile with gcc using the option -fno-implicit-templates.

When you build everything will be compiled as normal but then the collector will recompile the templates.cpp file for all the objects that use the template.

like image 86
Thaddeus Avatar answered Nov 15 '22 12:11

Thaddeus