Re: downcast to derived class in privately inherited base class templa
Georg Krichel wrote:
template< typename D >
class Base
{
public:
virtual ~Base( ) { ; }
void doFunc( )
{
D* dp = &dynamic_cast< D& >( *this ); // CRASH at runtime!
// ... more code using "dp"
}
};
class Derived : private Base< Derived >
{
friend class Base< Derived >;
public:
void doFunc( ) { Base< Derived >::doFunc( ); }
};
If Base<Derived> is inherited "public", it just works, if inherited
"protected", it will crash, too.
Yes, because Derived is not publicly convertible to Base<Derived>, it seems
the compiler ignores the friend declaration... If you want a definite
answer what is right, I'd ask in comp.lang.c++.moderated. FWIW, compiled
with the GCC 4.1 it shows the same behaviour at runtime.
But for other reasons I can't inherit "public" in the original
application's code, it must be a "private" inheritance.
Without knowing those reasons I obviously can't comment on that. The typical
reason to use the CRTP is to add something to a class' interface, so it is
non-typical to derive privately. I'd be interested to hear the background.
I want to use dynamic_cast to reference, because I want to have an
exception, if D is not derived from Base<D>.
Shouldn't that be handled like a programming error? In that case, I'd rather
use this code here:
assert(typeid(*this) == typeid(D));
....and then use a simple static_cast<> to convert to the derived class.
Uli