简体   繁体   中英

Is it acceptable to use pointers to class as enum constants?

Say I have some global objects:

MyClass* a = new MyClass()
MyClass* b = new MyClass()
MyClass* c = new MyClass()

Which repesent all meaningful states of MyClass

Is there a good reason not to form an enum from them as follows?

enum MyEnum {
    A = (int) a,
    B = (int) b,
    C = (int) c
}

Such that in other code, I can pass the enum around, and cast it: (MyClass*) (MyEnum::A)

That won't work. Enumerators can only be initialised with constant expressions, which your variables a , b , c definitely are not.

enum values are compile time constants, where as the return values of new are runtime values, as such you can not even do that (plus you would likely loose some data in the cast to int). I don't think it makes sense for SO to go into a lengthy discussion about whether it would be a good idea or not if it was possible.

As others already said, this is not possible. But you could achieve something similar with a singleton pattern, eg:

class MyClass
{
public:
    enum MyEnum { A, B, C };

    static MyClass* getAInstance()
    {
        static MyClass* a = new MyClass();
        return a;
    }

    static MyClass* getBInstance()
    {
        static MyClass* b = new MyClass();
        return b;
    }

    static MyClass* getCInstance()
    {
        static MyClass* c = new MyClass();
        return c;
    }

    static MyClass* getInstance(MyEnum instance)
    {
        switch(instance)
        {
        case A:
            return getAInstance();
        case B:
            return getBInstance();
        case C:
            return getCInstance();
        }
    }
};

So instead of (MyClass*) (MyEnum::A) you would write MyClass::getInstance(MyClass::A) .

I'm curius: why you need this implementation? By the way, I suggest you to use a vector/array with function pointer, if you need something for loop.

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