Search code examples
c++functiontemplatesradix

Is it legal to call a base class's template function in a child class?


Possible Duplicate:
“Undefined reference to” template class constructor

I've just started using templates, and I was wandering whether or not it is actually legal to call a template function in a child class. My problem is with the Template function ChangeSprite in the code below. It is being called in a child class, but this creates a linking error. If I remove the template part, and just give it one of the multiple things I plan on using it with instead it works fine, so I'm fearing that I won't be able to do this.

//base class
#pragma once  
#include "Tile.h"
#include <list>
#include "Sprite.h"
#include "WindowCreater.h"
#include "Directx.h"  
#define LeftClickParameters WindowCreator *gw, Mouse* mouse
struct Grid
{

    SPRITE *sprite;
    int width, hieght;
    int w, h;
    int x, y;
    Grid(int width, int hieght,SPRITE *sprites);
    list<Tile> tilew;
    list<list<Tile>> tileh;

    //methods

    void savefile();
    void openfile();
    virtual void MoveLeft() = 0;
    virtual void MoveRight() = 0;
    virtual void MoveUp() = 0;
    virtual void MoveDown() = 0;
    virtual void addrow() = 0;
    virtual void deleterow() = 0;
    virtual void addcolumb() = 0;
    virtual void deletecolumb() = 0;

    //template functions
    template <class T> void ChangeSprite(SPRITE *newSprite,list<T> tilew,list<list<T>> tileh);

    // Virtual methods
    virtual list<Tile> ReadTiles() = 0;
};    

and this is where it is being called

 //how the function is being called
 void Map::Brush(SPRITE *newSprite, POINT MousePosition)
 {
  Grid::ChangeSprite<MapTile>(newSprite,mapTilew,mapTileh);
 }

Solution

  • It can as long as Map inherits from Grid otherwise, you would have to make ChangeSprite static, or give it a Map object to act on. Here's a valid example of a child calling the parents templated function.

    struct Grid {
      template <class T> void ChangeSprite(/*params here*/) {
        // code here
      }
    };
    
    struct Map : public Grid {
        void Brush() {
            // bool being a placeholder for MapTile
            Grid::ChangeSprite<bool>(/*params here*/) {
                // code here
            }
        }
    };
    

    Your problem probably lies in the different files you're using, for instance templated functions should be defined in the header file, in or below your class definition.