Skip to content

Can't get runtime type of polymorphic object from pointer variant #388

@sinisastevanovic

Description

@sinisastevanovic

Problem:
I'm implementing a serialization system using RTTR and need to serialize polymorphic objects through base class pointers. When I have a variant containing a pointer to a base class (e.g.,ScriptableEntity*), but the actual object is a derived class (e.g., CameraController*), I want to serialize the properties of the actual derived type, not just the base class.

Current Setup:

class ScriptableEntity
{
    // Base class with RTTR registration
    RTTR_ENABLE()
};

registration::class_<ScriptableEntity>("ScriptableEntity")
			.constructor();

class CameraController : public ScriptableEntity
{
public:
    float Speed = 1.0f;  // Property I want to serialize
    RTTR_ENABLE(ScriptableEntity)
};

registration::class_<CameraController>("CameraController")
			.constructor()
			.property("Speed", &CameraController::Speed);

What works (but requires hardcoding):

if(Type.is_pointer() && Value.is_valid())
{
    auto raw = Value.convert<ScriptableEntity*>(); // Hardcoded base type
    auto actualType = rttr::type::get(*raw); // This works!
}

But how do I do this without knowing the base class? I am a bit stuck and can't seem to wrap my head around this. Maybe I am missing something obvious?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions