enum vs #define

How can I use enum like I would use the #define preprocessor macro?
For example, with #define, I can do something like :

#define STANDARD_RED_COLOR Vector3f(255, 0, 0)
#define STANDARD_BLUE_COLOR Vector3f(0, 0, 255)
#define STANDARD_GREEN_COLOR Vector3f(0, 255, 0)

int main(void) {
Vector3f greenColor = STANDARD_GREEN_COLOR;
Vector3f redColor = STANDARD_RED_COLOR;
Vector3f blueColor = STANDARD_BLUE_COLOR;
}

How can I accomplish this with an enumeration?
I'm not sure an enumeration is the right substitute.
Looks like you just want to define some constants.

1
2
3
const Vector3f STANDARD_RED_COLOR {255, 0, 0};
const Vector3f STANDARD_BLUE_COLOR {0, 0, 255};
const Vector3f STANDARD_GREEN_COLOR {0, 255, 0};
you cannot.
enums are integers. You can make a 4 byte integer hold the 3 bytes if that is useful.

you can do something similar to this (syntax may be wrong)
Vector3f[] colors = {{255,0,0},{0,0,255}, ... }etc
and an enum
{
red,green,blue,max;
};

and do this
colors[red];

but that does not really seem to be any more elegant here.

you can also get rid of the #defines and just make constant globals:

const Vector3f STANDARD_RED_COLOR (255, 0, 0); //cleaner than #define.
I highly recommend doing it this way, instead of #defines. There are multiple reasons including ease of debugging.

Last edited on
How can I accomplish this with an enumeration?

You can't.

But a macro is the wrong tool, anyways. You could instead write
constexpr Vector3f standard_red_color(255, 0, 0);

Edit: Sorry to repeat you @jonnin, I didn't see your post.
Last edited on
Thanks! I get it
Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Vector3f
{
    float first = 0, second = 0, third = 0 ;
    // ...
};

struct standard_colour
{
    static constexpr Vector3f red { 255, 0, 0 } ;
    static constexpr Vector3f green { 0, 255, 0 } ;
    static constexpr Vector3f blue { 0, 0, 255 } ;
    // etc.
};

int main()
{
    const auto clr_sky = standard_colour::blue ;
    // ...
    return int(clr_sky.first) ;
}

As a variant to @JLBorges, I would prefer to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdint>

struct color {
        uint8_t r, g, b;

        static constexpr color red() { return {255, 0, 0}; }
        static constexpr color green() { return {0, 255, 0}; }
        static constexpr color blue() { return {0, 0, 255}; }
};

int main() {
        auto r = color::red();
}


I'd prefer to keep the predefined colors in the color class, but then the problem with using static variables becomes struct literals from within the struct, which cannot occur. You would have to put them in another class or just constants hanging around in the namespace. However, putting them into a constexpr function allows you to return color literals.
Topic archived. No new replies allowed.