繁体   English   中英

如何从 C 样式 #define 和 struct 创建 c++ 枚举(或者这样做的正确方法是什么)?

[英]How to create a c++ enum from a C style #define and struct (or what's the right way to do this)?

我正在使用 C 库( Raylib ),它使用以下颜色表示:

#define RED        { 230, 41, 55, 255 }

// Color type, RGBA (32bit)
typedef struct Color {
  unsigned char r;
  unsigned char g;
  unsigned char b;
  unsigned char a;
} Color;

我想在C++代码中定义我将在调色板中使用的所有Color对象的枚举。

但是enum class只允许整数类型的值。 拥有固定的 static 一组非整数值的最佳方法是什么?

我想到的一种方法是在struct中声明static constexpr值。 这是正确的方法吗?

struct Color {
  constexpr static auto MYRED = RED;
  constexpr static auto MYBLUE = BLUE;
  constexpr static auto MYGREEN = GREEN;
};
namespace RayLib {
  using Color = ::Color;
  inline constexpr Color Red = RED;
  inline constexpr Color Blue = BLUE;
  inline constexpr Color Green = GREEN;
}

我会怎么做。

您可能还想要:

namespace MyApp {
  inline constexpr std::array Palette = {
    RayLib::Red,
    RayLib::Blue,
    RayLib::Green,
    RayLib::Fuscia
  };
}

其中MyApp是您用于应用程序特定代码的命名空间(在本例中,是您在应用程序中使用的调色板)。 (抱歉,如果我没有完全正确地得到上面的演绎语法)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM