我正在使用 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/