On 2005-06-27, Andy Lomax <abuse@[> wrote:[color=blue]
> I'm using a library where the supplier has provided base class 'foo',
> and a reference counting class which wraps 'foo':
>
> ------------------- library code -----------------------
> template<class T>
> refcount {
> ... // reference counting wrapper; like shared_ptr
> };
>
> class foo {
> ...
> };
>
> typedef refcount<foo> fooref;
> --------------------------------------------------------
>
> Now, when I use the library, I have to derive from 'foo' to make it
> useful. I also have to add a new function which is *not* declared
> virtual in 'foo':
>
> ----------------------- my code ------------------------
> class myfoo : public foo {
> ...
> void myfunc(void);
> }
> --------------------------------------------------------
>
> Problem: if I know that a 'fooref' actually points to a 'myfoo', how
> do I call 'myfunc'?
>
> void a(fooref b) {
> b->myfunc(); // compiler error: foo has no myfunc
> static_cast<myfooref>(b)->myfunc(); // 1
> static_cast<myfoo *>(&*b)->myfunc(); // 2
> }
>
> Both (1) and (2) compile, but are they the same thing? I understand
> (2), but (1) is more confusing. Can I cast a templated class in this
> way?[/color]
You can't generally cast anything to anything, no (and the different
parametrizations *are* allowed to be as unrelated as you like -- for example,
you could specialise one of them to inherit from vector<int>, and another to
inherit list<void*> if you wanted to). Depending on what conversion operators
refcount supports, it might work.
Now some thoughts --
(1) If you're casting down a class heirarchy, it would be safer to use a
dynamic cast. Then you get a runtime check to make sure you are really right
(and that it does really point to what you think it does)
(2) But it's better to avoid this. What is stopping you from making void a()
take a parameter of type myfoo instead ? If you've got several derived classes
of foo, you could factor them into a common base class. There are legitimate
uses for downtime casting, but the abuses are more common than the uses.
Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/