Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] C++ STL and template features compared with OCaml parametric polymorphism and OO features
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: skaller <skaller@u...>
Subject: Re: [Caml-list] C++ STL and template features compared with OCaml parametric polymorphism and OO features
On Tue, 2004-09-28 at 01:30, Brian Hurt wrote:
> On 28 Sep 2004, skaller wrote:

> > For templates all you need is a class with an operator()() method.
> > 
> > Dynamic dispatch is only needed if you need
> > run time function variables (first class functions).
> All this means is that the calling code, instead of calling foo->doit(), 
> now instead calls (*foo)().  Not that big of a difference in coding 
> volume.

The call is done by foo() which works for C functions, 
pointers to them, and function objects. This is required for 
STL to be generic.

> And you still need dynamic dispatch because you're passing the superclass
> type in.  

Type information is not required, the C++ compiler checks
the calls argument and return types after instantiation.

> Unless you're talking about templating the map/fold functions so
> that you get a different instantiation for each call?

Yes, because it costs nothing, which is much cheaper
than the virtual dispatch:

template<class F, class T> 
T apply(F f, T a) { return f(a); }

struct Sin { 
  float operator()(float a) const { return a; }

float (*pf)(float)= sin;


No dynamic dispatch is required here. The templates
works with C functions, pointers to C functions,
and function objects.

The first two calls should both resolve to 
just sin(1.0) (the call through the C pointer
requires an extra memory access .. :)

If you use a base and dynamic dispatch you'd incur
an overhead. Note the call is applied to a function
constant argument (the sine function).

Felix only uses dynamic dispatch when the function
is stored in a variable (or when it is too stupid
to optimise the call away by substitution).

BTW: note in the template, F is NOT the type
of the function -- it is the *class*
of the function. The actual function has type

	T -> T

The class of the function is irrelevant.

The class can even be float (*)(float),
it is still irrelavant -- what matters
is the type of f(a). For the function
object, that's a completely distinct
method with its own type -- unrelated
to the type of F: F is used solely
to lookup operator()() -- oh yeah,
that's ad hoc polymorphism.. :)

John Skaller,
voice: 061-2-9660-0850, 
snail: PO BOX 401 Glebe NSW 2037 Australia
Checkout the Felix programming language

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: