Re: Const Considerations (revisited)
On 3 Mrz., 01:45, "Craig Scott" <audiofana...@gmail.com> wrote:
I see some other possibilities:
3. You might use the handle-body idiom. The handle is the one that
registers to the subject and gets called via a const function. It then
delegates the request to the body and may use the non-const functions
in there.
If the handle gets notified via a const function, it cannot call non-
const functions without a const_cast. There are lots of ways out of
this if you are willing to use a const_cast, all of which involve
lying to your compiler. ;)
Well, the handle has a constant pointer to a non-const body object and
delegates the notification. Therefore you should be able to use non-
const functions of the body, even if the handle is a const object.
That would totally avoid const casts (but on the other hand give up
the possibility of these checks by the compiler... you'd have to
decide which way to die ;-) )
Some code partly 'stolen' from above ;-):
class Observer {
public:
virtual void OnEvent() const = 0;
};
class ObserverBody {
public:
virtual void OnEvent() = 0;
};
class ObserverHandle : public Observer {
private:
Observer* const pBody;
public:
virtual void OnEvent() const { pBody->OnEvent();}
};
Now you should be able to register all const Observers via deriving
from Observer and all others using a handle that points to the non-
const ObserverBody-derived class ...
It may be some overhead to create all the new handle
classes, but that should be quite easy by using a template
ObserverHandle class that will be generated when registering the
observer and deleted when deregistering.
Overhead is bad with observers. It can quickly start to limit their
usefulness when they end up getting called frequently. The goal should
be an efficient, low overhead observer which doesn't have to resort to
const_cast to get around things.
I was rather talking of the off-line overhead (i.e. your work when
creating the handle classes). Therefore I suggested a template -- but
having written the code, the above way seems more natural. The body
handle idiom would add a single additional virtual function call. I
wouldn't consider that overhead too big.
Nevertheless, even the body handle idiom would mean that you're just
hiding the information about const-ness to the compiler. So it would
not be 'lying' to the compiler, but 'talking to it about things, it
doesn't understand'. IMHO, the advantages should nevertheless
overweight the registering in two different subscription queues at the
subject that is to be observed.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]