Re: Virtual method inlining
On Wed, 2012-11-07, 1 2 wrote:
....
I hadn't thought of using compile-time polymorphism, but that's
probably because I think the lack of method signatures is a bit of a
problem. For example, with runtime polymorphism, you might have
something like this:
class Shape
{
public:
virtual void Draw(int x, int y) = 0;
};
void DrawShape(Shape* s)
{
s->Draw(200, 100);
}
With compile-time polymorphism, you would have:
// Note: no Shape base class
template<class Shape>
void DrawShape(Shape* s)
{
s->Draw(200, 100);
}
I'd prefer to pass a const reference, not a pointer to non-const.
It's not clear what operations the class supports, and what are the
parameter/return types of the methods. On the other hand, compile-time
polymorphism works nicely for things like STL iterators, where the
supported operations are clear from the nature of the object
(basically, iterators should behave as pointers).
Isn't the situation the same here, though? Shapes can be drawn. Just
document that, and trust the compiler to catch any errors.
On the other hand ...
I don't use run-time polymorphism much, and I don't like working with
it. I never used Smalltalk or Java. But when the alternative is a
huge switch statement even I find it preferable. Isn't this a
textbook example of such a case?
If you have to draw a changing bunch of mixed objects that means you
have to call various drawing functions, and you cannot statically
decide which ones in which order. You worry about the performance
penalty for virtual calls, but what alternative would be faster?
The same job still has to be done.
(The only optimization I can think of at the moment is to draw all Foo
objecte before all Bar objects, to keep the instruction cache warm.)
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .