Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 31,691 of 33,346    |
|    Martin B. to Kaba    |
|    Re: Mutable objects for std::set    |
|    24 Nov 11 12:40:52    |
      From: 0xCDCDCDCD@gmx.at              On 23.11.2011 17:10, Kaba wrote:       > Hi,       >       > ...       >       > As a good example of programming, the std::set enforces the invariant of       > unchanging keys, by making all external references to its objects const.       > This makes sure that changing a key does not happen by accident. On the       > other hand, this decision conflicts with genericity. I often find myself       > dealing with objects whose state can, and should, be freely changed       > without affecting their associated key. There are several hacks that can       > be used to work around this problem:       >       > 1) The first hack is to use the mutable keyword in the Type's member       > variables. ...       >       > 2) The second hack is to use const_cast for the object to gain access to       > modifying its state. This is more correct. ...       >       > 3) The third hack is to change to use std::map instead, by separating       > the key to its own object, and then associating it with the rest of the       > object. However, this is not always sufficient. ...       >       > The best practical approach at the moment, in my opinion, is to use the       > second hack of const_cast.       >       >...       > Of course, the same problem concerns std::unordered_set also.       >       > I don't know whether there is a better solution to the problem than the       > current one + const_cast. However, at least the problem has now been       > formulated.       >       > What are your thoughts?       >              Maybe for types that have a "key part" and a "non-key part" it might       make sense to wrap the type in something that can be put into the set       instead of the type. This wrapper would only allow the appropriate       modifications (possibly via const_cast or mutable).              I have to admit though that I'm out of luck thinking of how/if this       could be generically implemented in a sane way. :-)              cheers,       Martin                     --       I'm here to learn, you know.       Just waiting for someone,       to jump from the shadows,       telling me why I'm wrong.                      [ See http://www.gotw.ca/resources/clcm.htm for info about ]        [ comp.lang.c++.moderated. First time posters: Do this! ]              --- SoupGate-Win32 v1.05        * Origin: you cannot sedate... all the things you hate (1:229/2)    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca