Re: callbacks
{Please do not overquote - mod/we}
On Thursday, April 1, 1999 12:30:00 PM UTC+4:30, Andrei Alexandrescu wrote:
Dr. Michael Albert wrote in message ...
Hickey's solution consists of creating a "Functor" class which
contains a pointer to the object stored as void*, and a
pointer to the member function stored as a character array, and
I asked a similar question in this newsgroup, and I've got encouraging
answers.
Basically the standard guarantees that you can reinterpret_cast from a
pointer to a method of a class to a pointer to a method of another
class and back.
Some people correctly pointed out that MSVC (for instance) has a
compiler flag that optimizes the size of pointers to methods
considering the actual class layout and method population (whether or
not the class has virtuals, etc.).
I reached a solution that works with MSVC and ought to work with any
compiler because it has to. It's based upon the fact that you can
define a pointer to a method of an undefined class (sic!). For
instance:
class Button
{
class Foo;
void (Foo::*pMethod_)();
//...
};
Basically Foo will be only a placeholder and it won't be ever defined
in the application.
In this case, the compiler has no clue to optimize the size of the
pointer to member so it expects the worse and therefore sticks to the
most generic (biggest) mptr layout.
Next, when you have a pointer to some method of an object of yours,
you reinterpret_cast it into pMethod_. You know for sure it's going to
work, and you can even enforce this at compile time - just to be 100%
sure, with:
static_checker<(sizeof(MypMethod) <= sizeof(pMethod_)>();
Then (later on) you reinterpret_cast back the generic ptom into your
ptom, and that is going to work.
Here you are - no character arrays, no dynamic allocation, etc.
with variadic templates and rvalue referencing full forwarding is no
more a dream. Life is now very much sweeter. why don`t u wrap those
methods in a function template?
template < typename objectT
, typename retType, typename...ARGS
, retType objectT::*method(ARGS...)>
retType functor(objectT * that,ARGS&& ...params){
return that->method(params...);
}
I am afraid I might have missed the correct syntax of variadic
templates. Anyway, since the above template has static function
storage class, size of pointer to its instances is constant and equal,
- throughout smart utilization of non-dynamic casting - we can remove
the run-time cost of defining a polymorphic object_method interface
class. The minimal cost of pararmeter forwarding is style a matter
,but if trivial or refeernce/pointer types are used as method
arguments, auto optimizer may get the chance to eliminate the
overhead.
regards,
FM.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]