Struct with member tarray of itself

In standard C++, we can use vectors and maps as a means of a tree structure

struct Foo
{
    Foo();
    std::vector<Foo> subfoos;
};

But TArray/TMap cannot do this (by design). Is there a standard approach for handling this within Unreal’s syntax? The use case would be something like items that have their own inventory of items, etc.

USTRUCT()
struct Foo
{
    GENERATED_BODY()
    Foo();

    UPROPERTY()
    TArray<Foo> SubFoos; // No can do! :grimmace:
};

The only estimate I could come up with is holding some store of these structures and using a pointer to them. But as I currently understand the system that doesn’t hold up with replication.

Thanks so much!

Needed something quick so a solution was forged rather than found. While it may not be the perfect I settled on a flat table that can be rebuilt into a tree. To cut down on implementation minutia throughout the rest of the code, I used a little inheritance voodoo:

Base

The base provides us with a reusable, but blind, element.

USTRUCT()
struct FRecItemBase
{
    UPROPERTY()
    int32 Count;
    // ... Additional properties
};

Child

The child structure defines a resolution path and holds a base item. The path is an array to allow for a flat list to hold the tree data.

USTRUCT()
struct FRecItemChild
{
    TArray<FString> Path;
    FRecItemBase Item;
};

Item

Finally, the item contains an array of children (if required). This allows us to build objects on the stack but still contain a tree.

USTRUCT()
struct FRecItem : public FRecItemBase
{
    UPROPERTY()
    TArray<FRecItemChild> Children;

    // For converting to/from a base
    static FRecItem FromBase(const FItemBase& Base);
    FRecItemBase ToBase() const;
};

Usage

The inventory system holds an array of FRecItem objects, and when required, iterates over the children, generating proper FRectItem from the FRecItemBase children and passing them down the chain as required.

This tree, for our use cases, shouldn’t be very large (15 total elements is HUGE) so we’re not overly concerned with the stack. At least not yet.

2 Likes