rttrorg / rttr

C++ Reflection Library
https://www.rttr.org
MIT License
3.11k stars 429 forks source link

how to insert a class instrance into sequential view without get its wrapped value? #349

Open ray-linn opened 1 year ago

ray-linn commented 1 year ago

hi, Sir

I am creating a generic binary serializer, and got block on how to insert class instancec 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);
            //Item item=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. that is not what I want, because a serializer shall know nothing about his customer's type.

Could you help me to improve on this ?

Thank you.

BR Ray