c++ - 如何从 C 风格的 #define 和结构创建一个 C++ 枚举(或者什么是正确的方法)?

标签 c++ c++17

我正在使用 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 只允许整型值。拥有一组非整数的固定静态值的最佳方法是什么?

我想到的一种方法是在 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 是您用于应用程序特定代码的命名空间(在本例中,是您在应用程序中使用的调色板)。 (如果我没有完全理解上面的推导语法,我深表歉意)

关于c++ - 如何从 C 风格的 #define 和结构创建一个 C++ 枚举(或者什么是正确的方法)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58636627/

相关文章:

java - jfieldID 对于对象无效

c++ - 检查类型是否在可变参数模板参数包中传递

c++ - 使用 Apache Avro 时,c++17 出现段错误,但 c++11 不出现段错误

c++ - [expr.ref]/2 中的左值到右值转换

c++ - 如何在 g++ 中选择处理器(MIPS R2000)?

C++ 如何避免尾随零?

C++:热图 (BMP) 的数学函数

c++ - 序列点 - 这个 gcc 警告是一个错误吗?

c++ - 为什么 libc++ 不支持多重集上的类模板参数推导?

C++17 - 可变模板参数 - 使用模板参数调用先前返回值的类方法