【问题标题】:How to check, if the class is abstract, at compile time?如何在编译时检查类是否是抽象的?
【发布时间】:2014-01-26 20:52:45
【问题描述】:

我所说的抽象类是指具有至少一个纯虚方法的类。如果检查显示该类不是抽象,我希望编译失败。

有可能吗?

【问题讨论】:

  • 尝试创建一个实例吗?如果是抽象类,则不能有该类的实例。
  • @AlexandruBarbarosie 尝试创建它的实例也可能由于其他原因导致编译失败,例如私有构造函数,因此这不是一个防弹解决方案。
  • @rightfold 你是对的,但例如在this 的情况下,两个错误都会被考虑。

标签: c++ abstract-class compile-time static-assert


【解决方案1】:

使用std::is_abstract

#include <type_traits>

static_assert(std::is_abstract<T>(), "T ought to be abstract.");

in action

【讨论】:

  • 哇,不知道 STL 中存在这样的特征。
  • 这在 Visual Studio 2013 中无法编译。编译器认为 std::is_abstract 不是常量表达式!
  • 在VS2013中需要使用::value。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 2023-04-06
  • 2010-10-25
  • 1970-01-01
  • 2015-08-24
  • 2018-02-26
相关资源
最近更新 更多