rttrorg / rttr

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

[QUESTION] How to be more generic ? #230

Closed xallaume closed 5 years ago

xallaume commented 5 years ago

Hello, I'm trying to use RTTR in a gateway application where data types are compiled during the execution and loaded as an external library. I can load and use these data types with RTTR, but I'm trying to implement this in a generic way since I may deal with an unknown set of types. I can generate them since I know there names (as strings).

But at some point, I need to call a function that that has this data type as parameter. Let say: auto t = type::get_by_name( "DevicePosition" ); auto var = t.create();

    cout << "var.get_type().get_name() = " << var.get_type().get_name() << endl;

    auto p1 = t.get_property( "device_name" );
    p1.set_value(std::string( "testDevice" ));

    auto p2 = t.get_property( "longitude" );
    p2.set_value(var, double(1.4));

    auto p3 = t.get_property( "latitude" );
    p3.set_value(var, double(2.5));

    auto p4 = t.get_property( "altitude" );
    p4.set_value(var, double(3.6));

    for ( auto& prop : t.get_properties() )
    {
        if ( prop.get_name() == "device_name" )
            cout << "name: " << prop.get_name() << " value: " << variant_cast<std::string>( prop.get_value(var) ).in() << endl;
        else
            cout << "name: " << prop.get_name() << " value: " << prop.get_value( var ).to_string() << endl;
    }

    Gateway::DevicePositionDataWriter deviceposition_writer;

    Gateway::ReturnCode error = deviceposition_writer->write ( variant_cast<Gateway::DevicePosition>( var ) , null );

In this last function, I would dream of not having to write "" since I can't see how I could obtain that type in the generic part of the code (where I can only name the type through a string). Any idea here? And in the same time I can't understand why although a rttr::variant knows its type (which I get with var.get_type()), it can't return its base type without the need to provide the base type information in a templated signature function.

I hope I was clear enough, don't hesitate to ask for clarifications. Thank you very much in advance.

acki-m commented 5 years ago

I don't really get it. What is your problem with writing this: variant_cast<Gateway::DevicePosition>( var ) You have to know the exact type to extract it's value. When you store your value in a type safe container, you have to provide the type again to extract it later.

The 2nd question is also not understandable for me. Sorry.