Examples » Core » Reflection » Array Trait

Exposing and using array functionality of a type.

The ArrayTrait trait is used to expose the array functionality of a type. In this example, we will write a function which takes a type and an instance of that type, and prints its elements:

#include <cubos/core/reflection/traits/array.hpp>
#include <cubos/core/reflection/type.hpp>

using cubos::core::reflection::ArrayTrait;
using cubos::core::reflection::Type;

void printArray(const Type& type, const void* instance)
{
    const auto& arrayTrait = type.get<ArrayTrait>();

Through the trait, we can access the size of the array and its element type:

    auto arrayView = arrayTrait.view(instance);
    CUBOS_INFO("Array with {} elements of type {}", arrayView.length(), arrayTrait.elementType().name());

We can also get pointers to the elements of the array and iterate over them:

    if (!arrayTrait.elementType().is<int32_t>())
    {
        CUBOS_INFO("This function does not support printing arrays of types other than int32_t");
        return;
    }

    for (const auto* element : arrayView)
    {
        CUBOS_INFO("{}", *static_cast<const int32_t*>(element));
    }
}

In this example, we're only supporting arrays of int32_ts, but we could for example implement a printing function which supports all primitive types.

To make calling our function easier, we can add a convenience typed wrapper:

template <typename T>
void printArray(const T& array)
{
    using cubos::core::reflection::reflect;

    printArray(reflect<T>(), &array);
}

Using this function is now as simple as:

// You must also include <cubos/core/reflection/external/primitives.hpp> :)
#include <cubos/core/reflection/external/vector.hpp>

int main()
{
    std::vector<int32_t> vec = {1, 1, 2, 3, 5, 8, 13};
    printArray(vec);
}

Its important to note that both the includes above are necessary, as we're reflecting the type std::vector<int32_t>, which also means reflecting int32_t.

Executing the sample should output:

// Array with 7 elements of type int32_t
// 1
// 1
// 2
// 3
// 5
// 8
// 13