Added possibility to specify your own g_SHPtr / g_Plug, removed all occurencies of The Word, fixed UnloadPlugin and CompleteShutdown
2 // Efficient delegates in C++ that generate only two lines of asm code!
3 // Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp
5 // - Don Clugston, Mar 2004.
6 // Major contributions were made by Jody Hagins.
8 // 24-Apr-04 1.0 Submitted to CodeProject.
9 // 28-Apr-04 1.1 * Prevent most unsafe uses of evil static function hack.
10 // * Improved syntax for horrible_cast (thanks Paul Bludov).
11 // * Tested on Metrowerks MWCC and Intel ICL (IA32)
12 // * Compiled, but not run, on Comeau C++ and Intel Itanium ICL.
13 // 27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5
14 // * Now works on /clr "managed C++" code on VC7, VC7.1
15 // * Comeau C++ now compiles without warnings.
16 // * Prevent the virtual inheritance case from being used on
17 // VC6 and earlier, which generate incorrect code.
18 // * Improved warning and error messages. Non-standard hacks
19 // now have compile-time checks to make them safer.
20 // * implicit_cast used instead of static_cast in many cases.
21 // * If calling a const member function, a const class pointer can be used.
22 // * MakeDelegate() global helper function added to simplify pass-by-value.
23 // * Added fastdelegate.clear()
24 // 16-Jul-04 1.2.1* Workaround for gcc bug (const member function pointers in templates)
25 // 30-Oct-04 1.3 * Support for (non-void) return values.
26 // * No more workarounds in client code!
27 // MSVC and Intel now use a clever hack invented by John Dlugosz:
28 // - The FASTDELEGATEDECLARE workaround is no longer necessary.
29 // - No more warning messages for VC6
30 // * Less use of macros. Error messages should be more comprehensible.
31 // * Added include guards
32 // * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks).
33 // * Now tested on VS 2005 Beta, PGI C++
34 // 24-Dec-04 1.4 * Added DelegateMemento, to allow collections of disparate delegates.
35 // * <,>,<=,>= comparison operators to allow storage in ordered containers.
36 // * Substantial reduction of code size, especially the 'Closure' class.
37 // * Standardised all the compiler-specific workarounds.
38 // * MFP conversion now works for CodePlay (but not yet supported in the full code).
39 // * Now compiles without warnings on _any_ compiler, including BCC 5.5.1
40 // * New syntax: FastDelegate< int (char *, double) >.
42 #ifndef FASTDELEGATE_H
43 #define FASTDELEGATE_H
46 #endif // _MSC_VER > 1000
48 #include <memory.h> // to allow <,> comparisons
50 ////////////////////////////////////////////////////////////////////////////////
51 // Configuration options
53 ////////////////////////////////////////////////////////////////////////////////
55 // Uncomment the following #define for optimally-sized delegates.
56 // In this case, the generated asm code is almost identical to the code you'd get
57 // if the compiler had native support for delegates.
58 // It will not work on systems where sizeof(dataptr) < sizeof(codeptr).
59 // Thus, it will not work for DOS compilers using the medium model.
60 // It will also probably fail on some DSP systems.
61 #define FASTDELEGATE_USESTATICFUNCTIONHACK
63 // Uncomment the next line to allow function declarator syntax.
64 // It is automatically enabled for those compilers where it is known to work.
65 //#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
67 ////////////////////////////////////////////////////////////////////////////////
68 // Compiler identification for workarounds
70 ////////////////////////////////////////////////////////////////////////////////
72 // Compiler identification. It's not easy to identify Visual C++ because
73 // many vendors fraudulently define Microsoft's identifiers.
74 #if defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__VECTOR_C) && !defined(__ICL) && !defined(__BORLANDC__)
75 #define FASTDLGT_ISMSVC
77 #if (_MSC_VER <1300) // Many workarounds are required for VC6.
79 #pragma warning(disable:4786) // disable this ridiculous warning
84 // Does the compiler uses Microsoft's member function pointer structure?
85 // If so, it needs special treatment.
86 // Metrowerks CodeWarrior, Intel, and CodePlay fraudulently define Microsoft's
87 // identifier, _MSC_VER. We need to filter Metrowerks out.
88 #if defined(_MSC_VER) && !defined(__MWERKS__)
89 #define FASTDLGT_MICROSOFT_MFP
91 #if !defined(__VECTOR_C)
92 // CodePlay doesn't have the __single/multi/virtual_inheritance keywords
93 #define FASTDLGT_HASINHERITANCE_KEYWORDS
97 // Does it allow function declarator syntax? The following compilers are known to work:
98 #if defined(FASTDLGT_ISMSVC) && (_MSC_VER >=1310) // VC 7.1
99 #define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
102 // Gcc(2.95+), and versions of Digital Mars, Intel and Comeau in common use.
103 #if defined (__DMC__) || defined(__GNUC__) || defined(__ICL) || defined(__COMO__)
104 #define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
107 // It works on Metrowerks MWCC 3.2.2. From boost.Config it should work on earlier ones too.
108 #if defined (__MWERKS__)
109 #define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
112 #ifdef __GNUC__ // Workaround GCC bug #8271
113 // At present, GCC doesn't recognize constness of MFPs in templates
114 #define FASTDELEGATE_GCC_BUG_8271
119 ////////////////////////////////////////////////////////////////////////////////
120 // General tricks used in this code
122 // (a) Error messages are generated by typdefing an array of negative size to
123 // generate compile-time errors.
124 // (b) Warning messages on MSVC are generated by declaring unused variables, and
125 // enabling the "variable XXX is never used" warning.
126 // (c) Unions are used in a few compiler-specific cases to perform illegal casts.
127 // (d) For Microsoft and Intel, when adjusting the 'this' pointer, it's cast to
128 // (char *) first to ensure that the correct number of *bytes* are added.
130 ////////////////////////////////////////////////////////////////////////////////
133 ////////////////////////////////////////////////////////////////////////////////
136 namespace fastdelegate {
137 namespace detail { // we'll hide the implementation details in a nested namespace.
140 // I believe this was originally going to be in the C++ standard but
141 // was left out by accident. It's even milder than static_cast.
142 // I use it instead of static_cast<> to emphasize that I'm not doing
144 // Usage is identical to static_cast<>
145 template <class OutputClass, class InputClass>
146 inline OutputClass implicit_cast(InputClass input){
151 // This is truly evil. It completely subverts C++'s type system, allowing you
152 // to cast from any class to any other class. Technically, using a union
153 // to perform the cast is undefined behaviour (even in C). But we can see if
154 // it is OK by checking that the union is the same size as each of its members.
155 // horrible_cast<> should only be used for compiler-specific workarounds.
156 // Usage is identical to reinterpret_cast<>.
158 // This union is declared outside the horrible_cast because BCC 5.5.1
159 // can't inline a function with a nested class, and gives a warning.
160 template <class OutputClass, class InputClass>
161 union horrible_union{
166 template <class OutputClass, class InputClass>
167 inline OutputClass horrible_cast(const InputClass input){
168 horrible_union<OutputClass, InputClass> u;
169 // Cause a compile-time error if in, out and u are not the same size.
170 // If the compile fails here, it means the compiler has peculiar
171 // unions which would prevent the cast from working.
172 typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u)
173 && sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1];
178 ////////////////////////////////////////////////////////////////////////////////
181 ////////////////////////////////////////////////////////////////////////////////
183 // Backwards compatibility: This macro used to be necessary in the virtual inheritance
184 // case for Intel and Microsoft. Now it just forward-declares the class.
185 #define FASTDELEGATEDECLARE(CLASSNAME) class CLASSNAME;
187 // Prevent use of the static function hack with the DOS medium model.
189 #undef FASTDELEGATE_USESTATICFUNCTIONHACK
192 // DefaultVoid - a workaround for 'void' templates in VC6.
194 // (1) VC6 and earlier do not allow 'void' as a default template argument.
195 // (2) They also doesn't allow you to return 'void' from a function.
197 // Workaround for (1): Declare a dummy type 'DefaultVoid' which we use
198 // when we'd like to use 'void'. We convert it into 'void' and back
199 // using the templates DefaultVoidToVoid<> and VoidToDefaultVoid<>.
200 // Workaround for (2): On VC6, the code for calling a void function is
201 // identical to the code for calling a non-void function in which the
202 // return value is never used, provided the return value is returned
203 // in the EAX register, rather than on the stack.
204 // This is true for most fundamental types such as int, enum, void *.
205 // Const void * is the safest option since it doesn't participate
206 // in any automatic conversions. But on a 16-bit compiler it might
207 // cause extra code to be generated, so we disable it for all compilers
208 // except for VC6 (and VC5).
211 typedef const void * DefaultVoid;
213 // On any other compiler, just use a normal void.
214 typedef void DefaultVoid;
217 // Translate from 'DefaultVoid' to 'void'.
218 // Everything else is unchanged
220 struct DefaultVoidToVoid { typedef T type; };
223 struct DefaultVoidToVoid<DefaultVoid> { typedef void type; };
225 // Translate from 'void' into 'DefaultVoid'
226 // Everything else is unchanged
228 struct VoidToDefaultVoid { typedef T type; };
231 struct VoidToDefaultVoid<void> { typedef DefaultVoid type; };
235 ////////////////////////////////////////////////////////////////////////////////
236 // Fast Delegates, part 1:
238 // Conversion of member function pointer to a standard form
240 ////////////////////////////////////////////////////////////////////////////////
242 // GenericClass is a fake class, ONLY used to provide a type.
243 // It is vitally important that it is never defined, so that the compiler doesn't
244 // think it can optimize the invocation. For example, Borland generates simpler
245 // code if it knows the class only uses single inheritance.
247 // Compilers using Microsoft's structure need to be treated as a special case.
248 #ifdef FASTDLGT_MICROSOFT_MFP
250 #ifdef FASTDLGT_HASINHERITANCE_KEYWORDS
251 // For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP
252 // (4 bytes), even when the /vmg option is used. Declaring an empty class
253 // would give 16 byte pointers in this case....
254 class __single_inheritance GenericClass;
256 // ...but for Codeplay, an empty class *always* gives 4 byte pointers.
257 // If compiled with the /clr option ("managed C++"), the JIT compiler thinks
258 // it needs to load GenericClass before it can call any of its functions,
259 // (compiles OK but crashes at runtime!), so we need to declare an
260 // empty class to make it happy.
261 // Codeplay and VC4 can't cope with the unknown_inheritance case either.
262 class GenericClass {};
267 // The size of a single inheritance member function pointer.
268 const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)());
270 // SimplifyMemFunc< >::Convert()
272 // A template function that converts an arbitrary member function pointer into the
273 // simplest possible form of member function pointer, using a supplied 'this' pointer.
274 // According to the standard, this can be done legally with reinterpret_cast<>.
275 // For (non-standard) compilers which use member function pointers which vary in size
276 // depending on the class, we need to use knowledge of the internal structure of a
277 // member function pointer, as used by the compiler. Template specialization is used
278 // to distinguish between the sizes. Because some compilers don't support partial
279 // template specialisation, I use full specialisation of a wrapper struct.
281 // general case -- don't know how to convert it. Force a compile failure
283 struct SimplifyMemFunc {
284 template <class X, class XFuncType, class GenericMemFuncType>
285 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
286 GenericMemFuncType &bound_func) {
287 // Unsupported member function type -- force a compile failure.
288 // (it's illegal to have a array with negative size).
289 typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100];
294 // For compilers where all member func ptrs are the same size, everything goes here.
295 // For non-standard compilers, only single_inheritance classes go here.
297 struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE> {
298 template <class X, class XFuncType, class GenericMemFuncType>
299 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
300 GenericMemFuncType &bound_func) {
302 // Digital Mars doesn't allow you to cast between abitrary PMF's,
303 // even though the standard says you can. The 32-bit compiler lets you
304 // static_cast through an int, but the DOS compiler doesn't.
305 bound_func = horrible_cast<GenericMemFuncType>(function_to_bind);
307 bound_func = reinterpret_cast<GenericMemFuncType>(function_to_bind);
309 return reinterpret_cast<GenericClass *>(pthis);
313 ////////////////////////////////////////////////////////////////////////////////
314 // Fast Delegates, part 1b:
316 // Workarounds for Microsoft and Intel
318 ////////////////////////////////////////////////////////////////////////////////
321 // Compilers with member function pointers which violate the standard (MSVC, Intel, Codeplay),
322 // need to be treated as a special case.
323 #ifdef FASTDLGT_MICROSOFT_MFP
325 // We use unions to perform horrible_casts. I would like to use #pragma pack(push, 1)
326 // at the start of each function for extra safety, but VC6 seems to ICE
327 // intermittently if you do this inside a template.
329 // __multiple_inheritance classes go here
330 // Nasty hack for Microsoft and Intel (IA32 and Itanium)
332 struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > {
333 template <class X, class XFuncType, class GenericMemFuncType>
334 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
335 GenericMemFuncType &bound_func) {
336 // We need to use a horrible_cast to do this conversion.
337 // In MSVC, a multiple inheritance member pointer is internally defined as:
341 GenericMemFuncType funcaddress; // points to the actual member function
342 int delta; // #BYTES to be added to the 'this' pointer
345 // Check that the horrible_cast will work
346 typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1];
347 u.func = function_to_bind;
348 bound_func = u.s.funcaddress;
349 return reinterpret_cast<GenericClass *>(reinterpret_cast<char *>(pthis) + u.s.delta);
353 // virtual inheritance is a real nuisance. It's inefficient and complicated.
354 // On MSVC and Intel, there isn't enough information in the pointer itself to
355 // enable conversion to a closure pointer. Earlier versions of this code didn't
356 // work for all cases, and generated a compile-time error instead.
357 // But a very clever hack invented by John M. Dlugosz solves this problem.
358 // My code is somewhat different to his: I have no asm code, and I make no
359 // assumptions about the calling convention that is used.
361 // In VC++ and ICL, a virtual_inheritance member pointer
362 // is internally defined as:
363 struct MicrosoftVirtualMFP {
364 void (GenericClass::*codeptr)(); // points to the actual member function
365 int delta; // #bytes to be added to the 'this' pointer
366 int vtable_index; // or 0 if no virtual inheritance
368 // The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the
369 // m_codeptr member is *always* called, regardless of the values of the other
370 // members. (This is *not* true for other compilers, eg GCC, which obtain the
371 // function address from the vtable if a virtual function is being called).
372 // Dlugosz's trick is to make the codeptr point to a probe function which
373 // returns the 'this' pointer that was used.
375 // Define a generic class that uses virtual inheritance.
376 // It has a trival member function that returns the value of the 'this' pointer.
377 struct GenericVirtualClass : virtual public GenericClass
379 typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)();
380 GenericVirtualClass * GetThis() { return this; }
383 // __virtual_inheritance classes go here
385 struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 2*sizeof(int) >
388 template <class X, class XFuncType, class GenericMemFuncType>
389 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
390 GenericMemFuncType &bound_func) {
393 GenericClass* (X::*ProbeFunc)();
394 MicrosoftVirtualMFP s;
396 u.func = function_to_bind;
397 bound_func = reinterpret_cast<GenericMemFuncType>(u.s.codeptr);
399 GenericVirtualClass::ProbePtrType virtfunc;
400 MicrosoftVirtualMFP s;
402 // Check that the horrible_cast<>s will work
403 typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)
404 && sizeof(function_to_bind)==sizeof(u.ProbeFunc)
405 && sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1];
406 // Unfortunately, taking the address of a MF prevents it from being inlined, so
407 // this next line can't be completely optimised away by the compiler.
408 u2.virtfunc = &GenericVirtualClass::GetThis;
409 u.s.codeptr = u2.s.codeptr;
410 return (pthis->*u.ProbeFunc)();
416 // Nasty hack for Microsoft Visual C++ 6.0
417 // unknown_inheritance classes go here
418 // There is a compiler bug in MSVC6 which generates incorrect code in this case!!
420 struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
422 template <class X, class XFuncType, class GenericMemFuncType>
423 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
424 GenericMemFuncType &bound_func) {
425 // There is an apalling but obscure compiler bug in MSVC6 and earlier:
426 // vtable_index and 'vtordisp' are always set to 0 in the
427 // unknown_inheritance case!
428 // This means that an incorrect function could be called!!!
429 // Compiling with the /vmg option leads to potentially incorrect code.
430 // This is probably the reason that the IDE has a user interface for specifying
431 // the /vmg option, but it is disabled - you can only specify /vmg on
432 // the command line. In VC1.5 and earlier, the compiler would ICE if it ever
433 // encountered this situation.
434 // It is OK to use the /vmg option if /vmm or /vms is specified.
436 // Fortunately, the wrong function is only called in very obscure cases.
437 // It only occurs when a derived class overrides a virtual function declared
438 // in a virtual base class, and the member function
439 // points to the *Derived* version of that function. The problem can be
440 // completely averted in 100% of cases by using the *Base class* for the
441 // member fpointer. Ie, if you use the base class as an interface, you'll
442 // stay out of trouble.
443 // Occasionally, you might want to point directly to a derived class function
444 // that isn't an override of a base class. In this case, both vtable_index
445 // and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated.
446 // We can generate correct code in this case. To prevent an incorrect call from
447 // ever being made, on MSVC6 we generate a warning, and call a function to
448 // make the program crash instantly.
449 typedef char ERROR_VC6CompilerBug[-100];
457 // Nasty hack for Microsoft and Intel (IA32 and Itanium)
458 // unknown_inheritance classes go here
459 // This is probably the ugliest bit of code I've ever written. Look at the casts!
460 // There is a compiler bug in MSVC6 which prevents it from using this code.
462 struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
464 template <class X, class XFuncType, class GenericMemFuncType>
465 inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
466 GenericMemFuncType &bound_func) {
467 // The member function pointer is 16 bytes long. We can't use a normal cast, but
468 // we can use a union to do the conversion.
471 // In VC++ and ICL, an unknown_inheritance member pointer
472 // is internally defined as:
474 GenericMemFuncType m_funcaddress; // points to the actual member function
475 int delta; // #bytes to be added to the 'this' pointer
476 int vtordisp; // #bytes to add to 'this' to find the vtable
477 int vtable_index; // or 0 if no virtual inheritance
480 // Check that the horrible_cast will work
481 typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1];
482 u.func = function_to_bind;
483 bound_func = u.s.funcaddress;
484 int virtual_delta = 0;
485 if (u.s.vtable_index) { // Virtual inheritance is used
486 // First, get to the vtable.
487 // It is 'vtordisp' bytes from the start of the class.
488 const int * vtable = *reinterpret_cast<const int *const*>(
489 reinterpret_cast<const char *>(pthis) + u.s.vtordisp );
491 // 'vtable_index' tells us where in the table we should be looking.
492 virtual_delta = u.s.vtordisp + *reinterpret_cast<const int *>(
493 reinterpret_cast<const char *>(vtable) + u.s.vtable_index);
495 // The int at 'virtual_delta' gives us the amount to add to 'this'.
496 // Finally we can add the three components together. Phew!
497 return reinterpret_cast<GenericClass *>(
498 reinterpret_cast<char *>(pthis) + u.s.delta + virtual_delta);
501 #endif // MSVC 7 and greater
503 #endif // MS/Intel hacks
505 } // namespace detail
507 ////////////////////////////////////////////////////////////////////////////////
508 // Fast Delegates, part 2:
510 // Define the delegate storage, and cope with static functions
512 ////////////////////////////////////////////////////////////////////////////////
514 // DelegateMemento -- an opaque structure which can hold an arbitary delegate.
515 // It knows nothing about the calling convention or number of arguments used by
516 // the function pointed to.
517 // It supplies comparison operators so that it can be stored in STL collections.
518 // It cannot be set to anything other than null, nor invoked directly:
519 // it must be converted to a specific delegate.
522 // There are two possible implementations: the Safe method and the Evil method.
523 // DelegateMemento - Safe version
525 // This implementation is standard-compliant, but a bit tricky.
526 // A static function pointer is stored inside the class.
527 // Here are the valid values:
528 // +-- Static pointer --+--pThis --+-- pMemFunc-+-- Meaning------+
529 // | 0 | 0 | 0 | Empty |
530 // | !=0 |(dontcare)| Invoker | Static function|
531 // | 0 | !=0 | !=0 | Method call |
532 // +--------------------+----------+------------+----------------+
533 // When stored stored inside a specific delegate, the 'dontcare' entries are replaced
534 // with a reference to the delegate itself. This complicates the = and == operators
535 // for the delegate class.
537 // DelegateMemento - Evil version
539 // For compilers where data pointers are at least as big as code pointers, it is
540 // possible to store the function pointer in the this pointer, using another
541 // horrible_cast. In this case the DelegateMemento implementation is simple:
542 // +--pThis --+-- pMemFunc-+-- Meaning---------------------+
544 // | !=0 | !=0 | Static function or method call|
545 // +----------+------------+-------------------------------+
546 // Note that the Sun C++ and MSVC documentation explicitly state that they
547 // support static_cast between void * and function pointers.
549 class DelegateMemento {
551 // the data is protected, not private, because many
552 // compilers have problems with template friends.
553 typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP.
554 detail::GenericClass *m_pthis;
555 GenericMemFuncType m_pFunction;
557 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
558 typedef void (*GenericFuncPtr)(); // arbitrary code pointer
559 GenericFuncPtr m_pStaticFunction;
563 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
564 DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {};
566 m_pthis=0; m_pFunction=0; m_pStaticFunction=0;
569 DelegateMemento() : m_pthis(0), m_pFunction(0) {};
571 m_pthis=0; m_pFunction=0;
575 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
576 inline bool IsEqual (const DelegateMemento &x) const{
577 // We have to cope with the static function pointers as a special case
578 if (m_pFunction!=x.m_pFunction) return false;
579 // the static function ptrs must either both be equal, or both be 0.
580 if (m_pStaticFunction!=x.m_pStaticFunction) return false;
581 if (m_pStaticFunction!=0) return m_pthis==x.m_pthis;
585 inline bool IsEqual (const DelegateMemento &x) const{
586 return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction;
589 // Provide a strict weak ordering for DelegateMementos.
590 inline bool IsLess(const DelegateMemento &right) const {
591 // deal with static function pointers first
592 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
593 if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0)
594 return m_pStaticFunction < right.m_pStaticFunction;
596 if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis;
597 // There are no ordering operators for member function pointers,
598 // but we can fake one by comparing each byte. The resulting ordering is
599 // arbitrary (and compiler-dependent), but it permits storage in ordered STL containers.
600 return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0;
603 inline bool operator ! () const // Is it bound to anything?
604 { return m_pFunction==0; }
606 DelegateMemento & operator = (const DelegateMemento &right) {
607 SetMementoFrom(right);
610 inline bool operator <(const DelegateMemento &right) {
611 return IsLess(right);
613 inline bool operator >(const DelegateMemento &right) {
614 return right.IsLess(*this);
616 DelegateMemento (const DelegateMemento &right) :
617 m_pFunction(right.m_pFunction), m_pthis(right.m_pthis)
618 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
619 , m_pStaticFunction (right.m_pStaticFunction)
623 void SetMementoFrom(const DelegateMemento &right) {
624 m_pFunction = right.m_pFunction;
625 m_pthis = right.m_pthis;
626 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
627 m_pStaticFunction = right.m_pStaticFunction;
635 // A private wrapper class that adds function signatures to DelegateMemento.
636 // It's the class that does most of the actual work.
637 // The signatures are specified by:
638 // GenericMemFunc: must be a type of GenericClass member function pointer.
639 // StaticFuncPtr: must be a type of function pointer with the same signature
640 // as GenericMemFunc.
641 // UnvoidStaticFuncPtr: is the same as StaticFuncPtr, except on VC6
642 // where it never returns void (returns DefaultVoid instead).
644 // An outer class, FastDelegateN<>, handles the invoking and creates the
645 // necessary typedefs.
646 // This class does everything else.
650 template < class GenericMemFunc, class StaticFuncPtr, class UnvoidStaticFuncPtr>
651 class ClosurePtr : public DelegateMemento {
653 // These functions are for setting the delegate to a member function.
655 // Here's the clever bit: we convert an arbitrary member function into a
656 // standard form. XMemFunc should be a member function of class X, but I can't
657 // enforce that here. It needs to be enforced by the wrapper class.
658 template < class X, class XMemFunc >
659 inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) {
660 m_pthis = SimplifyMemFunc< sizeof(function_to_bind) >
661 ::Convert(pthis, function_to_bind, m_pFunction);
662 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
663 m_pStaticFunction = 0;
666 // For const member functions, we only need a const class pointer.
667 // Since we know that the member function is const, it's safe to
668 // remove the const qualifier from the 'this' pointer with a const_cast.
669 // VC6 has problems if we just overload 'bindmemfunc', so we give it a different name.
670 template < class X, class XMemFunc>
671 inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) {
672 m_pthis= SimplifyMemFunc< sizeof(function_to_bind) >
673 ::Convert(const_cast<X*>(pthis), function_to_bind, m_pFunction);
674 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
675 m_pStaticFunction = 0;
678 #ifdef FASTDELEGATE_GCC_BUG_8271 // At present, GCC doesn't recognize constness of MFPs in templates
679 template < class X, class XMemFunc>
680 inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) {
681 bindconstmemfunc(pthis, function_to_bind);
682 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
683 m_pStaticFunction = 0;
687 // These functions are required for invoking the stored function
688 inline GenericClass *GetClosureThis() const { return m_pthis; }
689 inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast<GenericMemFunc>(m_pFunction); }
691 // There are a few ways of dealing with static function pointers.
692 // There's a standard-compliant, but tricky method.
693 // There's also a straightforward hack, that won't work on DOS compilers using the
694 // medium memory model. It's so evil that I can't recommend it, but I've
695 // implemented it anyway because it produces very nice asm code.
697 #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
699 // ClosurePtr<> - Safe version
701 // This implementation is standard-compliant, but a bit tricky.
702 // I store the function pointer inside the class, and the delegate then
703 // points to itself. Whenever the delegate is copied, these self-references
704 // must be transformed, and this complicates the = and == operators.
706 // The next two functions are for operator ==, =, and the copy constructor.
707 // We may need to convert the m_pthis pointers, so that
708 // they remain as self-references.
709 template< class DerivedClass >
710 inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) {
712 if (m_pStaticFunction!=0) {
713 // transform self references...
714 m_pthis=reinterpret_cast<GenericClass *>(pParent);
717 // For static functions, the 'static_function_invoker' class in the parent
718 // will be called. The parent then needs to call GetStaticFunction() to find out
719 // the actual function to invoke.
720 template < class DerivedClass, class ParentInvokerSig >
721 inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
722 StaticFuncPtr function_to_bind ) {
723 bindmemfunc(pParent, static_function_invoker);
724 m_pStaticFunction=reinterpret_cast<GenericFuncPtr>(function_to_bind);
726 inline UnvoidStaticFuncPtr GetStaticFunction() const {
727 return reinterpret_cast<UnvoidStaticFuncPtr>(m_pStaticFunction);
731 // ClosurePtr<> - Evil version
733 // For compilers where data pointers are at least as big as code pointers, it is
734 // possible to store the function pointer in the this pointer, using another
735 // horrible_cast. Invocation isn't any faster, but it saves 4 bytes, and
736 // speeds up comparison and assignment. If C++ provided direct language support
737 // for delegates, they would produce asm code that was almost identical to this.
738 // Note that the Sun C++ and MSVC documentation explicitly state that they
739 // support static_cast between void * and function pointers.
741 template< class DerivedClass >
742 inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) {
743 SetMementoFrom(right);
745 // For static functions, the 'static_function_invoker' class in the parent
746 // will be called. The parent then needs to call GetStaticFunction() to find out
747 // the actual function to invoke.
748 // ******** EVIL, EVIL CODE! *******
749 template < class DerivedClass, class ParentInvokerSig>
750 inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
751 StaticFuncPtr function_to_bind) {
752 // We'll be ignoring the 'this' pointer, but we need to make sure we pass
753 // a valid value to bindmemfunc().
754 bindmemfunc(pParent, static_function_invoker);
756 // WARNING! Evil hack. We store the function in the 'this' pointer!
757 // Ensure that there's a compilation failure if function pointers
758 // and data pointers have different sizes.
759 // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
760 typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1];
761 m_pthis = horrible_cast<GenericClass *>(function_to_bind);
762 // MSVC, SunC++ and DMC accept the following (non-standard) code:
763 // m_pthis = static_cast<GenericClass *>(static_cast<void *>(function_to_bind));
764 // BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long
765 // m_pthis = reinterpret_cast<GenericClass *>(reinterpret_cast<long>(function_to_bind));
767 // ******** EVIL, EVIL CODE! *******
768 // This function will be called with an invalid 'this' pointer!!
769 // We're just returning the 'this' pointer, converted into
770 // a function pointer!
771 inline UnvoidStaticFuncPtr GetStaticFunction() const {
772 // Ensure that there's a compilation failure if function pointers
773 // and data pointers have different sizes.
774 // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
775 typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1];
776 return horrible_cast<UnvoidStaticFuncPtr>(this);
778 #endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
783 } // namespace detail
785 ////////////////////////////////////////////////////////////////////////////////
786 // Fast Delegates, part 3:
788 // Wrapper classes to ensure type safety
790 ////////////////////////////////////////////////////////////////////////////////
793 // Once we have the member function conversion templates, it's easy to make the
794 // wrapper classes. So that they will work with as many compilers as possible,
795 // the classes are of the form
796 // FastDelegate3<int, char *, double>
797 // They can cope with any combination of parameters. The max number of parameters
798 // allowed is 8, but it is trivial to increase this limit.
799 // Note that we need to treat const member functions seperately.
800 // All this class does is to enforce type safety, and invoke the delegate with
801 // the correct list of parameters.
803 // Because of the weird rule about the class of derived member function pointers,
804 // you sometimes need to apply a downcast to the 'this' pointer.
805 // This is the reason for the use of "implicit_cast<X*>(pthis)" in the code below.
806 // If CDerivedClass is derived from CBaseClass, but doesn't override SimpleVirtualFunction,
807 // without this trick you'd need to write:
808 // MyDelegate(static_cast<CBaseClass *>(&d), &CDerivedClass::SimpleVirtualFunction);
809 // but with the trick you can write
810 // MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction);
812 // RetType is the type the compiler uses in compiling the template. For VC6,
813 // it cannot be void. DesiredRetType is the real type which is returned from
814 // all of the functions. It can be void.
817 template<@CLASSARGS, class RetType=detail::DefaultVoid>
818 class FastDelegate@NUM {
820 typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
821 typedef DesiredRetType (*StaticFunctionPtr)(@FUNCARGS);
822 typedef RetType (*UnvoidStaticFunctionPtr)(@FUNCARGS);
823 typedef RetType (detail::GenericClass::*GenericMemFn)(@FUNCARGS);
824 detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> m_Closure;
826 // Typedefs to aid generic programming
827 typedef FastDelegate@NUM type;
829 // Construction and comparison functions
830 FastDelegate@NUM() { clear(); }
831 FastDelegate@NUM(const FastDelegate@NUM &x) {
832 m_Closure.CopyFrom(this, x.m_Closure); }
833 void operator = (const FastDelegate@NUM &x) {
834 m_Closure.CopyFrom(this, x.m_Closure); }
835 bool operator ==(const FastDelegate@NUM &x) const {
836 return m_Closure.IsEqual(x.m_Closure); }
837 bool operator !=(const FastDelegate@NUM &x) const {
838 return !m_Closure.IsEqual(x.m_Closure); }
839 bool operator <(const FastDelegate@NUM &x) const {
840 return m_Closure.IsLess(x.m_Closure); }
841 bool operator >(const FastDelegate@NUM &x) const {
842 return x.m_Closure.IsLess(m_Closure); }
843 // Binding to non-const member functions
844 template < class X, class Y >
845 FastDelegate@NUM(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) ) {
846 m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
847 template < class X, class Y >
848 inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS)) {
849 m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
850 // Binding to const member functions.
851 template < class X, class Y >
852 FastDelegate@NUM(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
853 m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
854 template < class X, class Y >
855 inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
856 m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
857 // Static functions. We convert them into a member function call.
858 // Note that this also provides a conversion from static functions.
859 FastDelegate@NUM(DesiredRetType (*function_to_bind)(@FUNCARGS) ) {
860 bind(function_to_bind); }
861 inline void bind(DesiredRetType (*function_to_bind)(@FUNCARGS)) {
862 m_Closure.bindstaticfunc(this, &FastDelegate@NUM::InvokeStaticFunction,
864 RetType operator() (@FUNCARGS) const { // Invoke the delegate
865 // this next line is the only one that violates the standard
866 return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(@INVOKEARGS); }
867 inline bool operator ! () const { // Is it bound to anything?
869 inline bool empty() const {
871 void clear() { m_Closure.clear();}
872 // Conversion to and from the DelegateMemento storage class
873 const DelegateMemento & GetMemento() { return m_Closure; }
874 void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
876 private: // Invoker for static functions
877 RetType InvokeStaticFunction(@FUNCARGS) const {
878 return (*(m_Closure.GetStaticFunction()))(@INVOKEARGS); }
883 ////////////////////////////////////////////////////////////////////////////////
884 // Fast Delegates, part 4:
886 // FastDelegate<> class (Original author: Jody Hagins)
887 // Allows boost::function style syntax like:
888 // FastDelegate< double (int, long) >
890 // FastDelegate2< int, long, double >
892 ////////////////////////////////////////////////////////////////////////////////
894 #ifdef FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
896 // Declare FastDelegate as a class template. It will be specialized
897 // later for all number of arguments.
898 template <typename Signature>
902 // Specialization to allow use of
903 // FastDelegate< R ( @SELARGS ) >
905 // FastDelegate@NUM < @SELARGS, R >
906 template<typename R, @CLASSARGS>
907 class FastDelegate< R ( @SELARGS ) >
908 // Inherit from FastDelegate@NUM so that it can be treated just
909 // like a FastDelegate@NUM
910 : public FastDelegate@NUM < @SELARGS, R >
913 // Make using the base type a bit easier via typedef.
914 typedef FastDelegate@NUM < @SELARGS, R > BaseType;
916 // Allow users access to the specific type of this delegate.
917 typedef FastDelegate SelfType;
919 // Mimic the base class constructors.
920 FastDelegate() : BaseType() { }
922 template < class X, class Y >
923 FastDelegate(Y * pthis,
924 R (X::* function_to_bind)( @FUNCARGS ))
925 : BaseType(pthis, function_to_bind) { }
927 template < class X, class Y >
928 FastDelegate(const Y *pthis,
929 R (X::* function_to_bind)( @FUNCARGS ) const)
930 : BaseType(pthis, function_to_bind)
933 FastDelegate(R (*function_to_bind)( @FUNCARGS ))
934 : BaseType(function_to_bind) { }
935 void operator = (const BaseType &x) {
936 *static_cast<BaseType*>(this) = x; }
941 #endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
943 ////////////////////////////////////////////////////////////////////////////////
944 // Fast Delegates, part 5:
946 // MakeDelegate() helper function
948 // MakeDelegate(&x, &X::func) returns a fastdelegate of the type
949 // necessary for calling x.func() with the correct number of arguments.
950 // This makes it possible to eliminate many typedefs from user code.
952 ////////////////////////////////////////////////////////////////////////////////
954 // Also declare overloads of a MakeDelegate() global function to
955 // reduce the need for typedefs.
956 // We need seperate overloads for const and non-const member functions.
957 // Also, because of the weird rule about the class of derived member function pointers,
958 // implicit downcasts may need to be applied later to the 'this' pointer.
959 // That's why two classes (X and Y) appear in the definitions. Y must be implicitly
962 // Workaround for VC6. VC6 needs void return types converted into DefaultVoid.
963 // GCC 3.2 and later won't compile this unless it's preceded by 'typename',
964 // but VC6 doesn't allow 'typename' in this context.
965 // So, I have to use a macro.
968 #define FASTDLGT_RETTYPE detail::VoidToDefaultVoid<RetType>::type
970 #define FASTDLGT_RETTYPE RetType
974 template <class X, class Y, @CLASSARGS, class RetType>
975 FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS)) {
976 return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
979 template <class X, class Y, @CLASSARGS, class RetType>
980 FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS) const) {
981 return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
986 // clean up after ourselves...
987 #undef FASTDLGT_RETTYPE
989 } // namespace fastdelegate
991 #endif // !defined(FASTDELEGATE_H)