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
(*blocks).bulletsCollition(player_bullets.getList());

//In header that the getList is declared
#ifndef BULLETLIST_H
#define BULLETLIST_H

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

struct Bullet:public Entity
{
    public:
        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
{
    public:
        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();
    protected:
    private:
    std::list<Bullet> bullets;
};


#endif // BULLETS_H


//The header where bulletsCollision is declared
class Ground
{
    public:
        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.

commented: Quick and helpful reply. Many thanks! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.