在c++中(在编译时)是否有办法强制派生类定义嵌套类型?
Is there any way to enforce in C++ (at compile-time) that a derived class defines a nested type?
例如,我有一个基类Event
,我想确保从Event
派生的每个类都定义了enum class Type
成员,因此T::Type
是从Event
派生的任何类T
的有效类型。
即使看了你的评论,我仍然不明白你的真正目的。但是要回答你问的具体问题:
您所要做的就是从派生类中使用类型,如果它不存在,您将得到编译错误。这是最简单的方法。
另一个稍微不同的直接方法是在事件类上使用模板化的策略类:
template <typename T>
struct EventType;
template <>
struct EventType<A>
{
typedef int Type;
};
因为只有模板才能以任何方式识别这样的东西,所以没有办法强制执行这样的限制。
仍然,你的模板可以使用sfinae来强制它们的约束,比如有一个名为alpha的类型成员,它是从beta派生出来的。
在你走这条路之前,确保你的努力是值得的。
我不知道用enum
实现这一点的方便方法,但也许实现目标的更简单方法可能是使用纯虚拟基类。
class Event
{
virtual int getType() = 0; // pure virtual function
};
class Circus : public Event
{
// Circus does not implement getType
};
int main()
{
Circus c; // compile-time error
}
相关文章:
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 为什么在VS2015中模板相关的嵌套类型名称中不需要typename关键字?
- 为什么嵌套类型的基类不需要"typename"?
- 如何在C++中的另一个模板函数中使用属于模板化类的嵌套类型?
- 保持嵌套类型的挥发性
- 具有嵌套类型的类的概念
- 将嵌套类型的类分开为标题和源
- 如何解决C++嵌套类型的循环依赖关系
- 在 C++11 中,从私有嵌套类型继承是否合法?
- C++ 递归嵌套类型和名称注入
- 如何定义一个模板类函数,该函数在类外的签名中具有嵌套类型的模板参数
- 访问模板参数T的嵌套类型,即使T是指针
- 为什么reverse_iterator双重定义其嵌套类型
- 嵌套类型:结构与类
- 如何对嵌套类型执行部分模板专用化
- 如何解析可选的嵌套类型,如 std::allocator_traits
- 模板和嵌套类型查找
- 派生类型可以与其基类的嵌套类型同名吗?
- C++ CRTP 并从 base 访问派生的嵌套类型定义
- 在c++中(在编译时)是否有办法强制派生类定义嵌套类型?