I'm trying to pass a list from a function to another using templates but get this error message:

/home/mattias/CodeBlocks/SpelBeta/src/player.cpp|64|undefined reference to `void Ground::bulletsCollition<Bullet>(std::list<Bullet, std::allocator<Bullet> >)'|

Here is the code:

//In the function calling the template function

//In header that the getList is declared

#include "entity.h"
#include <list>

struct Bullet:public Entity
        Bullet(int x,int y,int w,int h, int vel, int dmg):Entity(x,y,w,h){x_vel = vel; damage = dmg;};
        int x_vel, damage;

class BulletList
        void add(int x,int y,int w,int h, int vel, int dmg);
        void move(int);
        void display(SDL_Surface*);
        std::list<Bullet> getList();
    std::list<Bullet> bullets;

#endif // BULLETS_H

//The header where bulletsCollision is declared
class Ground
        bool collidesWith(SDL_Rect*);
        template <class Objects>
        void bulletsCollition(std::list<Objects>);
// And the actual function in the source file to that header

template <class Objects>
void Ground::bulletsCollition(std::list<Objects> bullets)

However if I skip the template part and pass a list of integers created in the calling function and atapt the code it compiles just fine.

Like this:

//template <class Objects>
void Ground::bulletsCollition(std::list<int> bullets)

What could be the problem?

You cannot separate the compilation of the function template from its declaration. Function templates are only compiled when they are used with a specific template argument, we call that instantiation. Your implementation of the function is never compiled in the cpp file because it is not used when you compile that cpp file, so the linker doesn't find it when you use it from another piece of code (translation unit).

The solution is that the implementation of that function template has to appear in the header file in which it is declared.

Read more about it here.

Quick and helpful reply. Many thanks!
This question has already been answered. Start a new discussion instead.