c++ - 限制模板化类数据类型

标签 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 派生的数据类型。有没有什么方法可以在运行时不使用动态转换和断言来实现这一点?

最佳答案

使用 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/

相关文章:

c++ - 当该参数的类型是模板类型时,如何提供默认参数参数?

c++ - 如何转发声明已在其他地方使用默认值转发声明的模板类型

c++模板函数用const参数覆盖参数推导

嵌套 lambda 中的 C++ 完美转发

C++11 反向基于范围的 for 循环

我定义的类的成员出现 C++ Vector 数据类型编译器错误问题

c++ - 不能在函数声明中使用模板参数

c++ - 函数参数的decltype

c++ - 重载运算符=,不同的类作为参数

c++ - 使用默认值参数丢弃函数指针上的参数是否有效?