Shorten path to C++ enum member (using typedef or typename), to use as template parameter

900 views Asked by At

I have a rather complicated object,

MyNamespace::MyClass::MySubStruct

which has an

enum
{
   ONE = 1,
   TWO = 2
};

Now I have another class which has a template parameter

template <unsigned int x> class Foo;

Currently I initialize B as follows

Foo<MyNamespace::MyClass::MySubStruct::ONE> MyFoo

and that works just fine, but it is a bit too lengthy, especially given that I initialize this class about a hundred times.

I would like to write something like:

typedef MyNamespace::MyClass::MySubStruct::ONE  MyONE
Foo<MyOne> MyFoo

Naturally, this does not compile, and neither does declaring it as a const unsigned int inside the class. How would one do this elegantly?

2

There are 2 answers

0
Columbo On BEST ANSWER

Enumerators are values, not types. If you only need this particular enumerator, declare a constant:

const auto MyONE = MyNamespace::MyClass::MySubStruct::ONE;

If you need more than only this one, it could be feasible to add a typedef for MySubStruct and access the enumerators through that.

0
Bartek Banachewicz On

ONE isn't a type; it's a value.

Instead of using typedef, you could simply use a constant:

const auto MyONE = MyNamespace::MyClass::MySubStruct::ONE;

Consider also using enum class instead of enum.