Boost logo

Boost :

Subject: Re: [boost] Formal Review Request: TypeErasure
From: Daniel Larimer (dlarimer_at_[hidden])
Date: 2012-06-13 10:25:45


>
> I have tried to see where I could use such types in the code I have
> been writing recently. I have found a good candidate where I need to
> pass a value across thread and library boundaries at the same time.
> The thread boundary implies that I want to copy the object, the
> library boundary that I'll loose type information (in that case).
> While this may not be the perfect use case, it helped me realise two
> things:
> - boost::variant is a good approximation of polymorphic value types,
> less convenient but may be faster (no dynamic memory management) and
> probably simpler to use.
> - I have no idea when and where one should use this paradigm. I had
> implied that the scope of TypeErasure was to replace inheritance–based
> polymorphism whenever possible. Now I think it may be more modest,
> though it is unclear to me what is the actual field of application.
> Could anyone tell me how they intend to use type erasure ?

        Suppose you wanted to create a graphics engine that would render any object that has a 'draw()' method. Currently you have two options: define a pure virtual base class and introduce a dependency between circle and square along with increasing the size of circle and square by the vtable pointer... or use a templates and do everything in the header file thus you no longer have a 'hidden' implementation and your compile times increase quickly.

        Assuming you use type erasure with references and therefore avoid the memory allocation, you can make any type polymorphic without introducing a vtable to your primitives.

        The primary use case for this technique in my mind is to move generic code from headers to source files and therefore maintaing better 'encapsulation' and separation between API and implementation. The users of the API get the same experience of using a template method, but now you get the benefit of a private (or closed source) implementation.

        I can now store a vector<squares> without waisting memory or having to worry about polymorphic destruction on my square or the fact that a vtable would mess with the binary representation of the squares preventing me from passing it to OpenCL without a transform to a non-polymorphic type.

        Think of this as 'non-intrusive' run-time polymorphism.

>
>
> Regards,
>
> Julien
>
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk