我有以下类定义:
// 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
类 StaticTile
和 DynamicTile
派生自 Tile
。目标是通过动态转换让 TileBase
中声明的方法出现在 Tile
的所有派生类中。
我想将 Tile
的模板定义限制为仅接受从 TileBase
派生的数据类型。有没有什么方法可以在运行时不使用动态转换和断言来实现这一点?
最佳答案
使用 std::is_base_of<>
很容易做到这一点
template<typename aTileBase>
class Tile : public aTileBase {
static_assert(std::is_base_of<TileBase, aTileBase>::value, "");
[...]
};
关于c++ - 限制模板化类数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117244/