← Back to team overview

kicad-developers team mailing list archive

Re: dyn_cast and ClassOf

 

On 06.06.2014 19:33, Lorenzo Marcantonio wrote:
Why reinventing the wheel? AFAIK C++ has a pretty good RTTI...
Doing it by hand seems to me quite error prone and distracting (and
I don't want to know what happens when subclassing). Had to do that in
the old borland C++ days (no templates, Borland intrusive containers),
didn't like it:D

Let's not get back to these dark, ancient times.

Either use only C++ RTTI or a type ID field. Mixing both is ugly.


In fact good design practices (at least in OO) would condemn the whole
KICAD_T enum :P

I think that instead of using such kind of expedient better (virtual)
interfaces (in the java sense, pure abstracts to be implemented) should
be designed with a refactoring.

This means a pretty much complete rewrite of Kicad...


That is, if you want to use C++ in the OO way (in imperative style I'd
simply have checked the type member, without all that template fluff).

I was reading Clang/LLVM source code and found this dyn_cast/isa pattern very elegant and lightweight. It's a mine of practical OO design ideas.

This template stuff has some advantages:
- it's much faster than C++ dynamic_cast,
- you don't have to remember the type ID <> class association (e.g. PCB_LINE_T vs class DRAWSEGMENT)
- can be implemented without disrupting the code
- saves a line (or three lines) of code on every down-cast:

Instead of:

if(item->Type() == something)
{
	DERIVED *x = static_cast<DERIVED *> item;
	single-line-action
}

all you need is:

if ( SOMETHING *x = dyn_cast<SOMETHING *>(item) )
	single-line-action

Regards,
Tom


Follow ups

References