在c++中(在编译时)是否有办法强制派生类定义嵌套类型?

Is there any way to enforce in C++ (at compile-time) that a derived class defines a nested type?

本文关键字:派生 嵌套类型 定义 c++ 编译 是否      更新时间:2023-10-16

例如,我有一个基类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
}