有没有一种模式可以让我从 C++ 中的另一个枚举继承枚举?
像这样的东西:
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
原文由 Sasha 发布,翻译遵循 CC BY-SA 4.0 许可协议
我的解决方案类似于上面的一些,除了我想在我的函数中返回一个枚举(采用 STATUS_ENUM 值的构造函数),并像一个枚举(将 STATUS_ENUM 值与类进行比较的运算符)进行比较。我还想要一种干净的方式来使用基类,而无需强制转换和检查(操作员覆盖)。最后,我想确保只有我指定的类型才能构造类(已删除的模板)。
struct StatusReturn
{
/**
* Use this to communicate trigger conditions internally to the caller.
* - Extend this class with a child who adds more static const STATUS_ENUM values as options.
* - When checking the return simply compare with != or == and the class will handle the rest.
* - This is true for a base class and a derived value, since this base class holds the value.
*/
typedef int STATUS_ENUM;
StatusReturn() = delete;
template <typename T>
StatusReturn(T) = delete;
StatusReturn(STATUS_ENUM value): _value(value) {};
// Operator overloads to compare the int to the class
friend bool operator==(const StatusReturn & lhs, const STATUS_ENUM & rhs)
{ return lhs.getValue() == rhs; };
friend bool operator!=(const StatusReturn & lhs, const STATUS_ENUM & rhs)
{ return !(lhs == rhs); };
friend bool operator==(const STATUS_ENUM & lhs, const StatusReturn & rhs)
{ return lhs == rhs.getValue(); };
friend bool operator!=(const STATUS_ENUM & lhs, const StatusReturn & rhs)
{ return !(lhs == rhs); };
// Non-exit triggering return
static const STATUS_ENUM CONTINUE = -1;
// Exit triggering values
static const STATUS_ENUM FAILED = 0;
static const STATUS_ENUM SUCCESS = 1;
static const STATUS_ENUM HALTED = 2;
STATUS_ENUM getValue() const
{ return _value; };
protected:
STATUS_ENUM _value = CONTINUE;
};
一些使用示例:
StatusReturn shouldExit()
{
return successBool ? StatusReturn::SUCCESS : StatusReturn::CONTINUE;
}
调用时看起来像:
auto exitValue = shouldExit();
if (exitValue != StatusReturn::CONTINUE)
{
return exitValue;
}
然后对派生类的检查是这样的:
auto exitValue = shouldExit();
if (exitValue != DerivedReturn::DO_STUFF)
{
return exitValue;
}
在这里,由于 DO_STUFF 也是 STATUS_ENUM 类型,因此运算符无需任何显式转换即可工作。
原文由 Ian A McElhenny 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
不可能。枚举没有继承。
您可以改为使用具有命名 const int 的类。
例子: