jeudi 24 novembre 2022

how to insert a class instance into RTTR sequential view without getting its wrapped value?

All

I am creating a generic binary serializer and got block on how to insert a class instance into a sequential view.

Here is the example code:

#include <iostream>
#include <rttr/type>
#include <rttr/registration.h>
using namespace rttr;

struct Item {
    int i ;
};
struct MyTestClass {
    std::vector<Item> seq;
};

RTTR_REGISTRATION
{
    using namespace rttr;
    registration::class_<MyTestClass>("TestClass")
        .constructor<>()
        .property("seq", &MyTestClass::seq);

    registration::class_<Item>("Item")
        .constructor<>()
        .property("item", &Item::i);

}

void CreateInst(rttr::instance inst) {
    auto localobj = inst.get_type().get_raw_type().is_wrapper() ? inst.get_wrapped_instance() : inst;
    auto p = localobj.get_type().get_property("item");
    p.set_value(inst, 100);
}

int main()
{
    MyTestClass inst;
    for (auto prop : rttr::type::get_by_name("TestClass").get_properties()) {
        auto type = prop.get_type();

        if (type.is_sequential_container()) {
            auto val = prop.get_value(inst);
            auto view =val.create_sequential_view();
            view.set_size(1); //just for demo
            rttr::variant var = view.get_value_type().create();
            CreateInst(var);
            //get its wrapped and insert 'it', it will have the correct result
            //Item it=var.get_wrapped_value<Item>(); 
            view.set_value(0, var);
            prop.set_value(inst, val);
        }
    }
    std::cout << inst.seq[0].i << std::endl;

}

it always output '0' instead of '100' on screen, unless I get its wrapped value and insert. But that is not what I want.

Could any expert help me to improve on this ?

Thank you.

BR Ray





Aucun commentaire:

Enregistrer un commentaire