In generic programming, static member functions and functors seem to
be very useful. I've noticed that some libraries take the approach of
using templated static member functions to provide generic
functionality, while others use functors. Take for example the
std::string char_traits class. Here, a static member "eq" is defined
to serve as a generic binary comparison function.
My implementation defines it as;
static bool eq(const char_type& c1, const char_type& c2) { return c1
== c2; }
An alternative would be to define eq as a functor, like:
struct eq {
bool operator() (const char_type c1, const char_type c2) { return
c1 == c2; }
}
The major difference, of course, is that the second case requires you
to instantiate the object. I originally thought that there wasn't
much difference, in terms of the actual assembly code generated,
between these two options. But benchmarking tests I've conduct show
that using an instantiated object is almost always faster than using a
static member function. I would have actually thought the opposite
would be true, because with an instantiated object you have the slight
additional overhead of constructing the object, whereas a static
member function is just like calling a global function.
But it seems that instantiated objects outperform static member
functions by a significant amount. My question is, is there some
inherent reason for this, or is this likely to be different from
compiler to compiler? Perhaps static member functions can't be
inlined.