Examples » Core » Reflection » Inherits Trait

Exposing the inheritance relationship between types.

For structured types, you might want to expose their inheritance relationships using InheritsTrait. This trait allows you to specify the parent type from which another type inherits.

In this example, we have three simple structs, GrandParent, Parent and Son, where Son is declared to inherit from Parent, and parent from GrandParent.

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

struct GrandParent
{
    CUBOS_REFLECT;
};

struct Parent
{
    CUBOS_REFLECT;
};

struct Son
{
    CUBOS_REFLECT;
};
#include <cubos/core/reflection/traits/inherits.hpp>

using cubos::core::reflection::InheritsTrait;
using cubos::core::reflection::Type;

CUBOS_REFLECT_IMPL(GrandParent)
{
    return Type::create("GrandParent");
}

CUBOS_REFLECT_IMPL(Parent)
{
    return Type::create("Parent").with(InheritsTrait::from<GrandParent>());
}

CUBOS_REFLECT_IMPL(Son)
{
    return Type::create("Son").with(InheritsTrait::from<Parent>());
}
template <typename T>
void reflectType()
{
    using cubos::core::reflection::reflect;

    const Type& type = reflect<T>();

    if (type.has<InheritsTrait>() && type.get<InheritsTrait>().inherits<Parent>())
    {
        CUBOS_INFO("{} inherits from Parent", type.name());
    }
    else
    {
        CUBOS_INFO("{} DOES NOT inherit from Parent", type.name());
    }

    if (type.has<InheritsTrait>() && type.get<InheritsTrait>().inherits<GrandParent>())
    {
        CUBOS_INFO("{} inherits from GrandParent", type.name());
    }
    else
    {
        CUBOS_INFO("{} DOES NOT inherit from GrandParent", type.name());
    }
}

int main()
{
    reflectType<Son>();
    reflectType<Parent>();
    reflectType<int>();
    return 0;
}

Output:

[15:30:10.611] [main.cpp:56 reflectType] info: "Son" inherits from Parent
[15:30:10.611] [main.cpp:65 reflectType] info: "Son" inherits from GrandParent
[15:30:10.611] [main.cpp:60 reflectType] info: "Parent" DOES NOT inherit from Parent
[15:30:10.611] [main.cpp:65 reflectType] info: "Parent" inherits from GrandParent
[15:30:10.611] [main.cpp:60 reflectType] info: "int" DOES NOT inherit from Parent
[15:30:10.611] [main.cpp:69 reflectType] info: "int" DOES NOT inherit from GrandParent