1
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?

6
  • If I understand correctly I think you want this: static_cast<int>(decltype(fruit_manager.group)::banana_fruit) Commented Sep 16, 2024 at 19:52
  • @NathanOliver WOAH yup, that works with FruitEnum group, that's magic, I've never used decltype, could you break down how that works a little more in a full answer? Commented Sep 16, 2024 at 20:01
  • Decltype gives the type of the expression or, when applied to class member type of the member (this case). See here. Commented Sep 16, 2024 at 20:13
  • @alagner thanks, just read that, and some of the pages it links... All this type figuring happens before runtime then, right? Do you have any recommends for like, sort of beginner-friendly resources on how compiler does all the type remembering and checking? It's kind of hard for me to imagine. Commented Sep 16, 2024 at 20:30
  • Yeah, that's compile-time. The problem with beginner-friendly type deduction is the fact, that it's not really a beginner friendly topic. You can try reading about l-p-r-x-values and try to understand them, but to me the best way to figure it out was to play around with decltype and type_traits. You may also want to have a look here Commented Sep 16, 2024 at 20:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.