简体   繁体   中英

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

I'm working with a C library ( Raylib ) that uses the following for color representation:

#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;

I want to define an enum of all the Color objects that I will use in my palette in my C++ code.

But enum class only allows integral kinds of values. What's the best way to have a fixed static set of values which are non-integral?

One approach I have in mind is just declare static constexpr values in a struct . Is this the right approach?

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;
}

is how I would do it.

You might also want:

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

where MyApp is the namespace you are using for app-specific code (in this case, the palette you are using in your app). (Apologies if I didn't get the deduction syntax quite right above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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