All Things C++

Death to TEnumAsByte!
February 17, 2024

It is one of the poorer practices that is filling the tutorial space of unreal engine c++. Enumerators (enums) are very useful for defining multiple types of a thing such as:

DefiningWhereTEnumAsByteIsNeeded.h

Copy Code

Copied!

Defining an enum like these leaves an issue when using them in TMaps or TArrays, the compiler will begin to tell you to enclose the type declaration in ‘TEnumAsByte’. Now while this will solve the error and bring that sweet relief of a green launch command. It would be better to look at what this is doing under the hood.

Where a Boolean sits as either a 0 (false) or 1 (true), think of an enumerator as a longer Boolean where we can have from 0 to UE_BIG_NUMBER, where each value corresponds with a name you’ve given:

So, using TEnumAsByte is simple do that conversion in the moment. But what are the drawbacks?

  • Extra code in declaring the type that could be done in the type definition that makes seeing that kind of error the most remote possibility.
  • Defining types that need TEnumAsByte put the type names in the global namespace for that class or even higher, this means that you may run into issues where you can’t have ‘None’ as the first type for two enums in the same file.

DeclaringUsingTEnumAsByte.h

DeclaringUsingTheBetterWay.h

Which is better?

The solution

Define your enums using enum class EYourEpicType : uint8!

Using the ‘class’ specifer encloses the names of your enum to the scope of itself (like any other class). So our fruit combo, best practice, would look like this:

UsingTheBetterWay.h

Copy Code

Copied!

This removes the need to use TEnumAsByte, translates seamlessly to blueprint with zero hassle, and allows for duplicate enum names enclosed in each scope! Happy coding.

Billboard summary

Swap TEnumAsByte to just your EAwesomeEnum by declaring your enum types using the ‘class’ specifier like so:

BestPractice.h

Copy Code

Copied!

Thanks for Reading!

See if Developd is the right fit for you.

Voluptatem Nostrum Tenetur
Velit
Voluptatum
Molestiae Et Officia
Velit
Voluptatem Nostrum Tenetur