Re: Calling a non-virtual member function for a NULL instance
Ivan Kolev wrote:
Matt Curtis wrote:
As a programmer I agree that undefined behaviour should be
avoided, however I also believe that this mechanism would be
quite useful if the standard allowed it.
I have a simple example where this "trick" is useful:
class IPlugin
{
public:
virtual IClassDesc& classDesc() const = 0;
};
template <class T>
IClassDesc& GetClassDesc()
{
return static_cast<T*>(0)->T::classDesc();
}
This allows to retrieve the IClassDesc of a class known at
compile time without forcing all IPlugin implementations to
implement both the virtual method classDesc() and an
additional static method ClassDesc(). If there are compilers
where the above will crash, is there a proper solution which
still avoids the double definition in each IPlugin-derived
class?
I don't think so. I also doubt that you'll find a compiler
where it will crash. On the other hand, I would definitly
prefer the two function solution, with the virtual function
forwarding to the static one. In the static function, I don't
have a this pointer, and so I cannot possibly accidentally use
it.
As for the extra boilerplate... if it is really a problem, I'd
use a macro. There are also tricks using an intermediate
template class, e.g.:
template< typename Derived >
class ConcretePlugin : public IPlugin
{
// ...
virtual IClassDesc& classDesc() const
{
assert( typeid( *this ) == typeid( Derived ) ) ;
return Derived::staticClassDesc() ;
}
} ;
Your derived classes then derive from ConcretePlugin<ClassName>,
rather than IPlugin.
IMHO: in this case, the added virtual function is simple enough
that it is not worth the bother to implement the more complex
solutions. In the case where you have a whole series of similar
functions (e.g. classDesc, className, clone, another...),
however, it might be.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]