簡體   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