Re: Virtual method inlining
On 8 nov, 11:34, Jorgen Grahn <grahn+n...@snipabacken.se> wrote:
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?
Exactly. In real code, a class might support quite a few methods
(maybe a couple dozen if it's part of a class hierarchy), and the
parameters for some of them can be more numerous and complicated than
in the example above.
Actually I just thought of a solution: combine the contracts provided
by runtime polymorphism with the fast calls of compile-time
polymorphism. We can define a COM interface or an abstract class for
the polymorphic operations:
interface IShape : IUnknown
{
HRESULT Draw(int x, int y);
}
And in the code that uses the polymorphic operations, we use a
template parameter, but make sure that it implements the interface by
using a static_assert that tests a std::is_base_of:
template<class Shape>
void DrawShape(Shape* s)
{
static_assert(std::is_base_of<IShape, Shape>::value, "Shape must
implement IShape");
s->Draw(200, 100);
}
I can definitely see this being used at large scale.