ForEach over Enums

Hello Guys,

I struggle to figure out how to do this as I’m still pretty new to C++ in general but I’m learning.
I basically wanna do a foreach loop over my enums and using that to set A local enum to find a value in a TMap to do some other things. For the life of me I cant figure out how to do the foreach over enums in c++.

This is an example of what I’m trying to accomplish any help would be appreciated!
Thanks,

Cody

C++ does not natively support this, because enum at the end when they are compiled are translated to integer values, each element get assigned number in order they been declared (you can also custom assign it by = operator but in you case you should not do that as as you see later). But because enum is treated same way as integers you can you can loop though integers insted. In UE4 convention you should have dummy last element called MAX indicating its last element, like in here:

then you can loop thru enum list by looping thru integers until MAX is reached, so using enum declared in link it would look like this:

for(int i; i < ETickingGroup::TG_MAX; i++) {

       //Do stuff

}
1 Like

I think there is a node which translates your enum number to the enum name. You could put that between the foreach node and the Find node.

I think I figured this out, but will not know until I do further testing so far its building find though.
If you go to EnumRange.h you will find some declarations of EnumRanges that you can use to be able to iterate over an enum.
Example Define:

ENUM_RANGE_BY_COUNT(ESomeType, ESomeType::Three)

Then I would use:

for (ESomeType Val : TEnumRange<ESomeType>())
{

}

Hoping this solves my problem and thanks for the answer. Also hopes this helps anybody else!

4 Likes

So I tried doing this and I’m getting an error: error C2677: binary ‘<’: no global operator found which takes type ‘EStatMetric’ (or there is no acceptable conversion).

Have any clue of what I might be doing wrong. I did try this way before and couldn’t get it to work.

Ah didn’t know about it :slight_smile:

When I was reading this solution I was confused. Then I tried this out of curiosity:
Add ENUM_RANGE_BY_COUNT(ESomeType, ESomeType::Three) to your header file, just above the class definition.

Then Use the second part of the code anywhere you want (obviously in your cpp file).
You’re done!

2 Likes

It is not really the answer to your question, but I provided a Solution for a Blueprint-Macro-Implementation.

My Enum is called Direction. Works like a charm.

3 Likes

You don’t need that macro. As shown in the original post, blueprint already has nodes that allow for iterating all the values of an enumeration.