c++ - 在子类中调用基类的模板函数是否合法?

标签 c++ function templates radix

<分区>

Possible Duplicate:
“Undefined reference to” template class constructor

我刚开始使用模板,我在犹豫在子类中调用模板函数是否真的合法。我的问题是下面代码中的模板函数 ChangeSprite。它在子类中被调用,但这会产生链接错误。如果我删除模板部分,只给它一个我计划使用它的多个东西之一,而不是它工作正常,所以我担心我无法做到这一点。

//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;
};    

这就是它被调用的地方

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

最佳答案

只要 Map 继承自 Grid 就可以,否则,你必须将 ChangeSprite 设为静态,或者给它一个 Map 对象进行操作。这是一个 child 调用 parent 模板函数的有效示例。

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
        }
    }
};

您的问题可能出在您使用的不同文件上,例如,模板函数应该在头文件中定义,在您的类定义中或下面。

关于c++ - 在子类中调用基类的模板函数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9057728/

相关文章:

c++ - gcc 和 class 关键字

c++ - 将类名插入容器

c++ - 基于条件然后三元运算符获取值的更快方法?

c++ - 创建一个依赖于模板类型的值常量

c++ - 仅在运行时给出签名时的函数指针调用

c++ - 初始化指向同名函数的静态成员函数指针

c++ - 在运行时选择模板参数时如何避免代码呈指数级增长

c++ - std::runtime_error 中的显式构造函数

ios - 'finish in' 在 Swift 中是什么意思?

Jquery $This 不适用于嵌套函数