Examples » Core » Reflection » Enum Trait

Exposing an enumeration with variants.

In this example, we'll explore how to expose an enumeration along with its variants using cubos::core::reflection::EnumTrait.

#include <cubos/core/reflection/reflect.hpp>

enum class Color
{
    Red,
    Green,
    Blue
};

CUBOS_REFLECT_EXTERNAL_DECL(CUBOS_EMPTY, Color);
#include <cubos/core/reflection/traits/enum.hpp>
#include <cubos/core/reflection/type.hpp>

using cubos::core::reflection::EnumTrait;
using cubos::core::reflection::Type;

CUBOS_REFLECT_EXTERNAL_IMPL(Color)
{
    return Type::create("Color").with(
        EnumTrait{}.withVariant<Color::Red>("Red").withVariant<Color::Green>("Green").withVariant<Color::Blue>("Blue"));
}

This section includes the necessary headers for reflection and defines the reflection for the Color enumeration.

Output:

int main()
{
    using cubos::core::reflection::reflect;

    const auto& colorType = reflect<Color>();
    CUBOS_ASSERT(colorType.has<EnumTrait>());

    const auto& variants = colorType.get<EnumTrait>();
    CUBOS_ASSERT(variants.contains("Red"));
    CUBOS_ASSERT(variants.contains("Green"));
    CUBOS_ASSERT(variants.contains("Blue"));
    CUBOS_ASSERT(!variants.contains("White"));

    Color c = Color::Red;
    CUBOS_ASSERT(variants.at("Red").test(&c));

    c = Color::Green;
    CUBOS_ASSERT(variants.at("Green").test(&c));

    c = Color::Blue;
    CUBOS_ASSERT(variants.at("Blue").test(&c));
    variants.at("Red").set(&c);
    CUBOS_ASSERT(variants.at("Red").test(&c));
    CUBOS_ASSERT(variants.at("Red").name() == "Red");
    CUBOS_ASSERT(variants.size() == 3);

    for (const auto& v : variants)
    {
        CUBOS_INFO("Variant {}", v.name());
    }

    CUBOS_INFO("{}", EnumTrait::toString(Color::Red)); // should print Red
    Color buf;
    CUBOS_ASSERT(EnumTrait::fromString(buf, "Green"));
    CUBOS_INFO("{}", EnumTrait::toString(buf)); // should print Green

    return 0;
}
[2023-11-19 13:09:36.117] [info] [main.cpp:59] Variant 'Red'
[2023-11-19 13:09:36.118] [info] [main.cpp:59] Variant 'Green'
[2023-11-19 13:09:36.119] [info] [main.cpp:59] Variant 'Blue'
[2023-11-19 13:09:36.119] [info] [main.cpp:62] 'Red'
[2023-11-19 13:09:36.119] [info] [main.cpp:65] 'Green'