Opened 3 years ago

Closed 19 months ago

#6720 closed enhancement (fixed)

Add a down_cast

Reported by: Kurt Schwehr Owned by: Kurt Schwehr
Priority: normal Milestone: 2.3.0
Component: default Version: unspecified
Severity: normal Keywords: casts dynamic_cast
Cc:

Description

Down casting (from a parent to child) can be done much better than GDAL does right now. e.g.

Random example:

https://trac.osgeo.org/gdal/browser/trunk/gdal/ogr/ogrgeometrycollection.cpp?rev=35912#L1168

        OGRGeometry* geom = papoGeoms[iGeom];
        OGRwkbGeometryType eType = wkbFlatten(geom->getGeometryType());
        if( OGR_GT_IsSurface(eType) )
        {
            dfArea += ((OGRSurface *) geom)->get_Area();
        }

We can do the following to my these dynamic_casts with a nullptr check:

        OGRSimpleCurve *poCurve = dynamic_cast<OGRSimpleCurve *>(poGeometry);
        if( poCurve == NULL )
        {
            CPLError(CE_Fatal, CPLE_AppDefined,
                     "dynamic_cast failed.  Expected OGRSimpleCurve.");
        }

But that sucks when we could have something like this:

// C++03
void yada( OGRGeometry *poGeom )
{
     OGRSimpleCurve *poCurve = down_cast<OGRSimpleCurve *>(poGeom);
     // ...
}

// C++14
void yada( OGRGeometry *poGeom )
{
     auto poCurve = down_cast<OGRSimpleCurve *>(poGeom);
     // poCurve is now an OGRSimpleCurve *.
     // ...

Where in DEBUG C++14 mode, things are fully checked. In all other modes, we do it the fastest way with no checking with a static_cast.

This could be adapted from the Google open source down_cast:

e.g. https://github.com/googlei18n/google-input-tools/blob/master/client/base/casts.h

and turned into port/cpl_casts.h

Change History (2)

comment:1 Changed 3 years ago by Kurt Schwehr

We would probably want to rename down_cast to CPLDownCast or CPL_down_cast or CPLdown_cast or cpl_down_cast or ?

Or we could finally declare what namespace GDAL should work towards.

I'd prefer gdal::down_cast or osgeo::gdal::down_cast.

But it could also be osgeo::cpl::down_cast, osgeo::gdal::port::down_cast, osgeo::gdal::cpl::downcast, or ...

Currently, I see:

Error: Failed to load processor bash
No macro or processor named 'bash' found

comment:2 Changed 19 months ago by Even Rouault

Milestone: 2.3.0
Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.