[multi_index] no non-const reference even for simple sorted container

Hi!
I tried to use multi_index_container as a drop in replacement
for std::map and hoped that I could obtain non-const references
to the values therein.
Although returning a non-const reference might not be a problem for
a multi_index_container with only 1 sorting criterium the lib
and the compiler insist on const &. Workarounds beyond modify(...) available?
Markus
#include
multi_t;
int main() { multi_t test; test.insert(boost::make_tuple("a", "aa")); // will not compile element & ref = test.find("a"); std::string & s = ref.get<1>(); }

Hello Markus, Markus Werle ha escrito:
Hi!
I tried to use multi_index_container as a drop in replacement for std::map and hoped that I could obtain non-const references to the values therein.
Although returning a non-const reference might not be a problem for a multi_index_container with only 1 sorting criterium the lib and the compiler insist on const &. Workarounds beyond modify(...) available?
(First of all, your statement
element & ref = test.find("a");
is incorrect in that it's missing an indirection. I assume your intended code is
element & ref = *test.find("a");
although it doesn't compile either because of the const & issue you complain
about.)
B.MI always returns const references to the elements so as to not allow
the user to modify the keys on her own. This has nothing to do with whether
the number of indices is one or more, so I don't quite get your reasoning.
If we could get a non-const reference the following violation of the internal
invariants of B.MI would pass at compile time:
element & ref = test.find("a");
ref.get<0>()="b"; // boom
So, in order to get non-const access to the second member of your tuple
(as the first must be kept untouched since it's a key), you've got to somehow
circumvent this protective measure. There are several alternatives.
1. Use const_cast to eliminate constness
const element & ref = *test.find("a");
std::string & s = const_cast
participants (2)
-
Joaquín Mª López Muñoz
-
Markus Werle