简体   繁体   中英

Storing enum values from another namespace in an array

I would like to store the values from an enum variable in another namespace in an array.

So assuming the enum is declared as follows

namespace something
{
    enum IWANT
    {
        FOO = 0,
        BAR,
        BLARGH,
        MEH,
        SIZE
    };
} // namespace SOMETHING

and I can access this enum else were using

something::FOO

Is it possible to store certain variables I want from something in an array? For example

<varType> onlyWhatIwant[3] = {something::FOO, something::BAR, something::SIZE}

Such that when the variable is used as follows onlyWhatIwant[1] points to the something::BAR

I don't know if this is even possible or not but thought I would ask before looking for another route.

Enums are basically a way to define integer constants; they don't have some address associated so that you can have a pointer to them in the traditional sense. What you want to do is possible to some extent (check my full example below); however, the array elements will not point to something else. They will just have the value equal to the assigned constant (foo::first and foo::second, in my example).

namespace foo {
    enum X {first, second};
};

int main() {
    foo::X t[3] = {foo::first, foo::first, foo::second};
    return 0;
}

for an enum like this

namespace something{
  enum myEnum{
    Val0 = 0,
    Val1 = 1,
    Val2 = 2,
    Val3 = 3,
  //...
  //Valn = n
  };
}

you can also use something like this as an alias for values

enum onlywhatiwant{
  Val1 = something::Val1,
  Val3 = something::Val3
  // etc
};

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