c++ - #define inside an enum 或如何扩展枚举

标签 c++ enums macros c-preprocessor

我有几个类,每个类都使用相同的 enum,但根据其要求对其进行了一些扩展。 例如:

class skirtColor{
  enum Color{
red = 1,
blue = 10,
green = 12
};
};
class dressColor {
enum Color{
red = 1,
pink,
yellow,
blue = 10,
green = 12
};
};
class pantsColor {
enum Color {
red = 1,
brown,
blue = 10,
green = 12
};
};

由于在C++中枚举没有继承,所以我想用define作为公共(public)部分

#define COLOR\
// red color \
red = 1,\
// blue color \
blue = 10,\
//green color
green = 12,

之后我可以在类中重用常见的颜色定义

class skirtColor{
  enum Color{
COLOR
};
};
class dressColor {
enum Color{
COLOR
pink = 2,
yellow,
};
};
Class pantsColor {
enum Color {
COLOR
brown = 2,
};
};

这样可以吗? 我无法编译这段代码你能帮我正确定义宏吗?

最佳答案

目前您可以管理此类事情的一种方法是继承,它将继承类中的常量。

struct Color
{
     enum { red = 1, blue = 10, green = 12 };
} ;

struct DressColor : Color
{
     enum { pink =2, yellow = 3 };
};

DressColor 也会有红色、蓝色和绿色..

如果你想启用“严格类型化”以拥有一个必须具有这些值之一的变量,你可以使用一个“具有”值并且只能在类内构造或修改的类来实现。

struct Color
{
    class Holder
    {
        private:
        int value;
        explicit Holder( int v ) : value( v ) {}

        public:
        bool operator==( const Holder & other ) const
        {
            return value == other.value;
        }

        int get() const
        {
            return value;
        }

        friend struct Color;
    };

  protected:        
    static Holder makeHolder( int v )
    {
        return Holder( v );
    }

  public:
    static const Holder red;
    static const Holder blue;
    static const Holder green;
};


struct DressColor : Color
{
    static const Holder pink;
    static const Holder yellow;
};

     // these in a .cpp file.
const Color::Holder Color::red( 1 );
const Color::Holder Color::blue( 10 );
const Color::Holder Color::green( 12 );
const Color::Holder DressColor::pink( Color::makeHolder(2) );
const Color::Holder DressColor::yellow( Color::makeHolder(3) );

     // how you can create a variable of one. Note that whilst you cannot construct
     // a Color::Holder from an int in the regular way, you can copy-construct.

     Color::Holder var( Color::red );

当然,在这个“解决方法”中,枚举对象仍然是 Color::Holder 类型,不能是 DressColor::Holder 类型以使用 DressColor 类

关于c++ - #define inside an enum 或如何扩展枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14277671/

相关文章:

c++ - 在堆栈展开时使用 RAII 是否安全?

clojure - 为什么这个 clojure 宏需要 `' ~?

for-loop - 如何在for循环中运行jupyter笔记本宏

c++ - CodeLite 未指定可执行文件,使用 'target exec' 错误

c++ - 如何在 ListView 控件中制作复选框三态?

c++ - 使用 g++ 从 cpp 文件和静态库创建共享库

java - 如何有效地返回当前数据中心的字符串基础?

java - 使用 JPA 映射枚举

python - 在 python 3 中遍历枚举时,并非所有元素都出现

C预处理器: macro function to call printf()