限制模板化类的数据类型

时间:2018-06-30 17:48:03

标签: c++ templates

我有以下类定义:

// A TileBase contains a deceleration for game events that will be present in 
// Static and Dynamic tiles
class TileBase

// To use tiles in your game, create a tile base for Tile to inherit from, then 
// create game-specific tiles as derivitives of StaticTile or DynamicTile
template<typename aTileBase> class Tile : public aTileBase

StaticTileDynamicTile源自Tile。目标是通过动态转换在TileBase的所有派生类中的Tile中声明方法。

我想将Tile的模板定义限制为仅接受从TileBase派生的数据类型。有什么方法可以在运行时不使用动态强制转换和断言来实现这一目标?

1 个答案:

答案 0 :(得分:4)

使用std::is_base_of<>

很容易
template<typename aTileBase> 
class Tile : public aTileBase {
  static_assert(std::is_base_of<TileBase, aTileBase>::value, "");

  [...]
};