rttrorg / rttr

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

[QUESTION] Set value of variant_associative_view element #227

Closed vamidi closed 5 years ago

vamidi commented 5 years ago

Hi there,

I created a variable of std::map and reflected it with RTTR. when I am looping throught the variant_associative_view I can grab the key and the value, but the problem is now how do I set the value of an element that I find?

Thanks in advance!

acki-m commented 5 years ago

At the moment the only solution to do this, is that you have to use a const_cast See following example code:

auto map = std::map<int, std::string>{ { 1, "one" }, { 2, "two" }, { 3, "three" } };
variant var = map;
variant_associative_view view = var.create_associative_view();
auto itr = view.find(1);
auto& foo = const_cast<std::string&>(itr.get_value().get_wrapped_value <std::string>());
foo = "one B";
std::cout << itr.get_value().to_string(); // prints "one B"

I could add a non-const version to the itr.get_value() function. But I do not remember anymore why I did not do it...mhm. Does this workaround your problem?

vamidi commented 5 years ago

I am going to try it out and let you know immediately. Thanks for the help! Another question, but I think it will probably be awnsered if I have implemented this workaround. But my question is will that update the property when I give it the element inside the property a new value? Also why do I need const_cast?

vamidi commented 5 years ago

To come back on const_cast I looked it up and it makes sense. Thanks, learned something new!

acki-m commented 5 years ago

For sure the key cannot be changed, however, I do not see a problem, why the value cannot be changed...

vamidi commented 5 years ago

Yes just like a normal map I had to delete and insert again if you want to change the key, which is fine, but I tried the workaround that you mentioned. It worked, however there is a catch in order to set the value inside the map you need to know the type or base type, which is not always convient, because normally in a variant_sequential_view you can do if(!rArrView.set_value(uiIndex, NewValue)). Is there no possibility to make a set_value function that you can give the key as first parameter and second the new value?