c++templatesenum-class

Accessing the Enum Class used to make a Templated Struct C++


template <typename FruitEnum>
struct FruitManager
{
    FruitEnum group
};

enum class FirstFruitEnum
{
    apple_fruit,
    banana_fruit,
};

enum class SecondFruitEnum
{
    banana_fruit,
    grape_fruit,
};

int main()
{
    FruitManager<FirstFruitEnum> fruit_manager;
}

I am trying to set up something that would work like

int index = static_cast<int>(fruit_manager.group::banana_fruit);

(equivalent in output to this)

int index = static_cast<int>(FirstFruitEnum::banana_fruit);

For context, the struct is able to be created with either enum class. How is this best done?


Solution

  • decltype can be used to get the type of the group member and once you have the type you can then access the enumeration.

    decltype(fruit_manager.group)
    

    gives you the type of group and then

    decltype(fruit_manager.group)::banana_fruit
    

    is how you access the enum member of the enum type that group has.