core-legacy/sourcehook/generate/FastDelegate.hxx
author David Anderson <dvander@alliedmods.net>
Sat Oct 15 22:16:50 2011 -0700 (2011-10-15)
changeset 767 fd3ff8d792ce
parent 545 07e5df11f9fc
permissions -rw-r--r--
Fix page protection bug causing a rare startup crash (bug 5133, r=fyren).
dvander@541
     1
//						FastDelegate.h
dvander@541
     2
//	Efficient delegates in C++ that generate only two lines of asm code!
dvander@541
     3
//  Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp
dvander@541
     4
//
dvander@541
     5
//						- Don Clugston, Mar 2004.
dvander@541
     6
//		Major contributions were made by Jody Hagins.
dvander@541
     7
// History:
dvander@541
     8
// 24-Apr-04 1.0  * Submitted to CodeProject.
dvander@541
     9
// 28-Apr-04 1.1  * Prevent most unsafe uses of evil static function hack.
dvander@541
    10
//				  * Improved syntax for horrible_cast (thanks Paul Bludov).
dvander@541
    11
//				  * Tested on Metrowerks MWCC and Intel ICL (IA32)
dvander@541
    12
//				  * Compiled, but not run, on Comeau C++ and Intel Itanium ICL.
dvander@541
    13
//	27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5
dvander@541
    14
//				  * Now works on /clr "managed C++" code on VC7, VC7.1
dvander@541
    15
//				  * Comeau C++ now compiles without warnings.
dvander@541
    16
//				  * Prevent the virtual inheritance case from being used on
dvander@541
    17
//					  VC6 and earlier, which generate incorrect code.
dvander@541
    18
//				  * Improved warning and error messages. Non-standard hacks
dvander@541
    19
//					 now have compile-time checks to make them safer.
dvander@541
    20
//				  * implicit_cast used instead of static_cast in many cases.
dvander@541
    21
//				  * If calling a const member function, a const class pointer can be used.
dvander@541
    22
//				  * MakeDelegate() global helper function added to simplify pass-by-value.
dvander@541
    23
//				  * Added fastdelegate.clear()
dvander@541
    24
// 16-Jul-04 1.2.1* Workaround for gcc bug (const member function pointers in templates)
dvander@541
    25
// 30-Oct-04 1.3  * Support for (non-void) return values.
dvander@541
    26
//				  * No more workarounds in client code!
dvander@541
    27
//					 MSVC and Intel now use a clever hack invented by John Dlugosz:
dvander@541
    28
//				     - The FASTDELEGATEDECLARE workaround is no longer necessary.
dvander@541
    29
//					 - No more warning messages for VC6
dvander@541
    30
//				  * Less use of macros. Error messages should be more comprehensible.
dvander@541
    31
//				  * Added include guards
dvander@541
    32
//				  * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks).
dvander@541
    33
//				  * Now tested on VS 2005 Express Beta, PGI C++
dvander@541
    34
// 24-Dec-04 1.4  * Added DelegateMemento, to allow collections of disparate delegates.
dvander@541
    35
//                * <,>,<=,>= comparison operators to allow storage in ordered containers.
dvander@541
    36
//				  * Substantial reduction of code size, especially the 'Closure' class.
dvander@541
    37
//				  * Standardised all the compiler-specific workarounds.
dvander@541
    38
//                * MFP conversion now works for CodePlay (but not yet supported in the full code).
dvander@541
    39
//                * Now compiles without warnings on _any_ supported compiler, including BCC 5.5.1
dvander@541
    40
//				  * New syntax: FastDelegate< int (char *, double) >.
dvander@541
    41
// 14-Feb-05 1.4.1* Now treats =0 as equivalent to .clear(), ==0 as equivalent to .empty(). (Thanks elfric).
dvander@541
    42
//				  * Now tested on Intel ICL for AMD64, VS2005 Beta for AMD64 and Itanium.
dvander@541
    43
// 30-Mar-05 1.5  * Safebool idiom: "if (dg)" is now equivalent to "if (!dg.empty())"
dvander@541
    44
//				  * Fully supported by CodePlay VectorC
dvander@541
    45
//                * Bugfix for Metrowerks: empty() was buggy because a valid MFP can be 0 on MWCC!
dvander@541
    46
//                * More optimal assignment,== and != operators for static function pointers.
dvander@541
    47
dvander@541
    48
#ifndef FASTDELEGATE_H
dvander@541
    49
#define FASTDELEGATE_H
dvander@541
    50
dvander@541
    51
#ifdef _MSC_VER
dvander@541
    52
# if _MSC_VER > 1000
dvander@541
    53
#  pragma once
dvander@541
    54
# endif // _MSC_VER > 1000
dvander@541
    55
#endif // #ifdef _MSC_VER
dvander@541
    56
dvander@541
    57
#include <memory.h> // to allow <,> comparisons
dvander@541
    58
dvander@541
    59
////////////////////////////////////////////////////////////////////////////////
dvander@541
    60
//						Configuration options
dvander@541
    61
//
dvander@541
    62
////////////////////////////////////////////////////////////////////////////////
dvander@541
    63
dvander@541
    64
// Uncomment the following #define for optimally-sized delegates.
dvander@541
    65
// In this case, the generated asm code is almost identical to the code you'd get
dvander@541
    66
// if the compiler had native support for delegates.
dvander@541
    67
// It will not work on systems where sizeof(dataptr) < sizeof(codeptr).
dvander@541
    68
// Thus, it will not work for DOS compilers using the medium model.
dvander@541
    69
// It will also probably fail on some DSP systems.
dvander@541
    70
#define FASTDELEGATE_USESTATICFUNCTIONHACK
dvander@541
    71
dvander@541
    72
// Uncomment the next line to allow function declarator syntax.
dvander@541
    73
// It is automatically enabled for those compilers where it is known to work.
dvander@541
    74
//#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
    75
dvander@541
    76
////////////////////////////////////////////////////////////////////////////////
dvander@541
    77
//						Compiler identification for workarounds
dvander@541
    78
//
dvander@541
    79
////////////////////////////////////////////////////////////////////////////////
dvander@541
    80
dvander@541
    81
// Compiler identification. It's not easy to identify Visual C++ because
dvander@541
    82
// many vendors fraudulently define Microsoft's identifiers.
dvander@541
    83
#if defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__VECTOR_C) && !defined(__ICL) && !defined(__BORLANDC__)
dvander@541
    84
#define FASTDLGT_ISMSVC
dvander@541
    85
dvander@541
    86
#if (_MSC_VER <1300) // Many workarounds are required for VC6.
dvander@541
    87
#define FASTDLGT_VC6
dvander@541
    88
#pragma warning(disable:4786) // disable this ridiculous warning
dvander@541
    89
#endif
dvander@541
    90
dvander@541
    91
#endif
dvander@541
    92
dvander@541
    93
// Does the compiler uses Microsoft's member function pointer structure?
dvander@541
    94
// If so, it needs special treatment.
dvander@541
    95
// Metrowerks CodeWarrior, Intel, and CodePlay fraudulently define Microsoft's
dvander@541
    96
// identifier, _MSC_VER. We need to filter Metrowerks out.
dvander@541
    97
#if defined(_MSC_VER) && !defined(__MWERKS__)
dvander@541
    98
#define FASTDLGT_MICROSOFT_MFP
dvander@541
    99
dvander@541
   100
#if !defined(__VECTOR_C)
dvander@541
   101
// CodePlay doesn't have the __single/multi/virtual_inheritance keywords
dvander@541
   102
#define FASTDLGT_HASINHERITANCE_KEYWORDS
dvander@541
   103
#endif
dvander@541
   104
#endif
dvander@541
   105
dvander@541
   106
// Does it allow function declarator syntax? The following compilers are known to work:
dvander@541
   107
#if defined(FASTDLGT_ISMSVC) && (_MSC_VER >=1310) // VC 7.1
dvander@541
   108
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
   109
#endif
dvander@541
   110
dvander@541
   111
// Gcc(2.95+), and versions of Digital Mars, Intel and Comeau in common use.
dvander@541
   112
#if defined (__DMC__) || defined(__GNUC__) || defined(__ICL) || defined(__COMO__)
dvander@541
   113
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
   114
#endif
dvander@541
   115
dvander@541
   116
// It works on Metrowerks MWCC 3.2.2. From boost.Config it should work on earlier ones too.
dvander@541
   117
#if defined (__MWERKS__)
dvander@541
   118
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
   119
#endif
dvander@541
   120
dvander@541
   121
#ifdef __GNUC__ // Workaround GCC bug #8271
dvander@541
   122
	// At present, GCC doesn't recognize constness of MFPs in templates
dvander@541
   123
#define FASTDELEGATE_GCC_BUG_8271
dvander@541
   124
#endif
dvander@541
   125
dvander@541
   126
dvander@541
   127
dvander@541
   128
////////////////////////////////////////////////////////////////////////////////
dvander@541
   129
//						General tricks used in this code
dvander@541
   130
//
dvander@541
   131
// (a) Error messages are generated by typdefing an array of negative size to
dvander@541
   132
//     generate compile-time errors.
dvander@541
   133
// (b) Warning messages on MSVC are generated by declaring unused variables, and
dvander@541
   134
//	    enabling the "variable XXX is never used" warning.
dvander@541
   135
// (c) Unions are used in a few compiler-specific cases to perform illegal casts.
dvander@541
   136
// (d) For Microsoft and Intel, when adjusting the 'this' pointer, it's cast to
dvander@541
   137
//     (char *) first to ensure that the correct number of *bytes* are added.
dvander@541
   138
//
dvander@541
   139
////////////////////////////////////////////////////////////////////////////////
dvander@541
   140
//						Helper templates
dvander@541
   141
//
dvander@541
   142
////////////////////////////////////////////////////////////////////////////////
dvander@541
   143
dvander@541
   144
dvander@541
   145
namespace fastdelegate {
dvander@541
   146
namespace detail {	// we'll hide the implementation details in a nested namespace.
dvander@541
   147
dvander@541
   148
//		implicit_cast< >
dvander@541
   149
// I believe this was originally going to be in the C++ standard but
dvander@541
   150
// was left out by accident. It's even milder than static_cast.
dvander@541
   151
// I use it instead of static_cast<> to emphasize that I'm not doing
dvander@541
   152
// anything nasty.
dvander@541
   153
// Usage is identical to static_cast<>
dvander@541
   154
template <class OutputClass, class InputClass>
dvander@541
   155
inline OutputClass implicit_cast(InputClass input){
dvander@541
   156
	return input;
dvander@541
   157
}
dvander@541
   158
dvander@541
   159
//		horrible_cast< >
dvander@541
   160
// This is truly evil. It completely subverts C++'s type system, allowing you
dvander@541
   161
// to cast from any class to any other class. Technically, using a union
dvander@541
   162
// to perform the cast is undefined behaviour (even in C). But we can see if
dvander@541
   163
// it is OK by checking that the union is the same size as each of its members.
dvander@541
   164
// horrible_cast<> should only be used for compiler-specific workarounds.
dvander@541
   165
// Usage is identical to reinterpret_cast<>.
dvander@541
   166
dvander@541
   167
// This union is declared outside the horrible_cast because BCC 5.5.1
dvander@541
   168
// can't inline a function with a nested class, and gives a warning.
dvander@541
   169
template <class OutputClass, class InputClass>
dvander@541
   170
union horrible_union{
dvander@541
   171
	OutputClass out;
dvander@541
   172
	InputClass in;
dvander@541
   173
};
dvander@541
   174
dvander@541
   175
template <class OutputClass, class InputClass>
dvander@541
   176
inline OutputClass horrible_cast(const InputClass input){
dvander@541
   177
	horrible_union<OutputClass, InputClass> u;
dvander@541
   178
	// Cause a compile-time error if in, out and u are not the same size.
dvander@541
   179
	// If the compile fails here, it means the compiler has peculiar
dvander@541
   180
	// unions which would prevent the cast from working.
dvander@541
   181
	typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u)
dvander@541
   182
		&& sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1];
dvander@541
   183
	u.in = input;
dvander@541
   184
	return u.out;
dvander@541
   185
}
dvander@541
   186
dvander@541
   187
////////////////////////////////////////////////////////////////////////////////
dvander@541
   188
//						Workarounds
dvander@541
   189
//
dvander@541
   190
////////////////////////////////////////////////////////////////////////////////
dvander@541
   191
dvander@541
   192
// Backwards compatibility: This macro used to be necessary in the virtual inheritance
dvander@541
   193
// case for Intel and Microsoft. Now it just forward-declares the class.
dvander@541
   194
#define FASTDELEGATEDECLARE(CLASSNAME)	class CLASSNAME;
dvander@541
   195
dvander@541
   196
// Prevent use of the static function hack with the DOS medium model.
dvander@541
   197
#ifdef __MEDIUM__
dvander@541
   198
#undef FASTDELEGATE_USESTATICFUNCTIONHACK
dvander@541
   199
#endif
dvander@541
   200
dvander@541
   201
//			DefaultVoid - a workaround for 'void' templates in VC6.
dvander@541
   202
//
dvander@541
   203
//  (1) VC6 and earlier do not allow 'void' as a default template argument.
dvander@541
   204
//  (2) They also doesn't allow you to return 'void' from a function.
dvander@541
   205
//
dvander@541
   206
// Workaround for (1): Declare a dummy type 'DefaultVoid' which we use
dvander@541
   207
//   when we'd like to use 'void'. We convert it into 'void' and back
dvander@541
   208
//   using the templates DefaultVoidToVoid<> and VoidToDefaultVoid<>.
dvander@541
   209
// Workaround for (2): On VC6, the code for calling a void function is
dvander@541
   210
//   identical to the code for calling a non-void function in which the
dvander@541
   211
//   return value is never used, provided the return value is returned
dvander@541
   212
//   in the EAX register, rather than on the stack.
dvander@541
   213
//   This is true for most fundamental types such as int, enum, void *.
dvander@541
   214
//   Const void * is the safest option since it doesn't participate
dvander@541
   215
//   in any automatic conversions. But on a 16-bit compiler it might
dvander@541
   216
//   cause extra code to be generated, so we disable it for all compilers
dvander@541
   217
//   except for VC6 (and VC5).
dvander@541
   218
#ifdef FASTDLGT_VC6
dvander@541
   219
// VC6 workaround
dvander@541
   220
typedef const void * DefaultVoid;
dvander@541
   221
#else
dvander@541
   222
// On any other compiler, just use a normal void.
dvander@541
   223
typedef void DefaultVoid;
dvander@541
   224
#endif
dvander@541
   225
dvander@541
   226
// Translate from 'DefaultVoid' to 'void'.
dvander@541
   227
// Everything else is unchanged
dvander@541
   228
template <class T>
dvander@541
   229
struct DefaultVoidToVoid { typedef T type; };
dvander@541
   230
dvander@541
   231
template <>
dvander@541
   232
struct DefaultVoidToVoid<DefaultVoid> {	typedef void type; };
dvander@541
   233
dvander@541
   234
// Translate from 'void' into 'DefaultVoid'
dvander@541
   235
// Everything else is unchanged
dvander@541
   236
template <class T>
dvander@541
   237
struct VoidToDefaultVoid { typedef T type; };
dvander@541
   238
dvander@541
   239
template <>
dvander@541
   240
struct VoidToDefaultVoid<void> { typedef DefaultVoid type; };
dvander@541
   241
dvander@541
   242
dvander@541
   243
dvander@541
   244
////////////////////////////////////////////////////////////////////////////////
dvander@541
   245
//						Fast Delegates, part 1:
dvander@541
   246
//
dvander@541
   247
//		Conversion of member function pointer to a standard form
dvander@541
   248
//
dvander@541
   249
////////////////////////////////////////////////////////////////////////////////
dvander@541
   250
dvander@541
   251
// GenericClass is a fake class, ONLY used to provide a type.
dvander@541
   252
// It is vitally important that it is never defined, so that the compiler doesn't
dvander@541
   253
// think it can optimize the invocation. For example, Borland generates simpler
dvander@541
   254
// code if it knows the class only uses single inheritance.
dvander@541
   255
dvander@541
   256
// Compilers using Microsoft's structure need to be treated as a special case.
dvander@541
   257
#ifdef  FASTDLGT_MICROSOFT_MFP
dvander@541
   258
dvander@541
   259
#ifdef FASTDLGT_HASINHERITANCE_KEYWORDS
dvander@541
   260
	// For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP
dvander@541
   261
	// (4 bytes), even when the /vmg option is used. Declaring an empty class
dvander@541
   262
	// would give 16 byte pointers in this case....
dvander@541
   263
	class __single_inheritance GenericClass;
dvander@541
   264
#endif
dvander@541
   265
	// ...but for Codeplay, an empty class *always* gives 4 byte pointers.
dvander@541
   266
	// If compiled with the /clr option ("managed C++"), the JIT compiler thinks
dvander@541
   267
	// it needs to load GenericClass before it can call any of its functions,
dvander@541
   268
	// (compiles OK but crashes at runtime!), so we need to declare an
dvander@541
   269
	// empty class to make it happy.
dvander@541
   270
	// Codeplay and VC4 can't cope with the unknown_inheritance case either.
dvander@541
   271
	class GenericClass {};
dvander@541
   272
#else
dvander@541
   273
	class GenericClass;
dvander@541
   274
#endif
dvander@541
   275
dvander@541
   276
// The size of a single inheritance member function pointer.
dvander@541
   277
const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)());
dvander@541
   278
dvander@541
   279
//						SimplifyMemFunc< >::Convert()
dvander@541
   280
//
dvander@541
   281
//	A template function that converts an arbitrary member function pointer into the
dvander@541
   282
//	simplest possible form of member function pointer, using a supplied 'this' pointer.
dvander@541
   283
//  According to the standard, this can be done legally with reinterpret_cast<>.
dvander@541
   284
//	For (non-standard) compilers which use member function pointers which vary in size
dvander@541
   285
//  depending on the class, we need to use	knowledge of the internal structure of a
dvander@541
   286
//  member function pointer, as used by the compiler. Template specialization is used
dvander@541
   287
//  to distinguish between the sizes. Because some compilers don't support partial
dvander@541
   288
//	template specialisation, I use full specialisation of a wrapper struct.
dvander@541
   289
dvander@541
   290
// general case -- don't know how to convert it. Force a compile failure
dvander@541
   291
template <int N>
dvander@541
   292
struct SimplifyMemFunc {
dvander@541
   293
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   294
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   295
		GenericMemFuncType &bound_func) {
dvander@541
   296
		// Unsupported member function type -- force a compile failure.
dvander@541
   297
	    // (it's illegal to have a array with negative size).
dvander@541
   298
		typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100];
dvander@541
   299
		return 0;
dvander@541
   300
	}
dvander@541
   301
};
dvander@541
   302
dvander@541
   303
// For compilers where all member func ptrs are the same size, everything goes here.
dvander@541
   304
// For non-standard compilers, only single_inheritance classes go here.
dvander@541
   305
template <>
dvander@541
   306
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE>  {
dvander@541
   307
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   308
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   309
			GenericMemFuncType &bound_func) {
dvander@541
   310
#if defined __DMC__
dvander@541
   311
		// Digital Mars doesn't allow you to cast between abitrary PMF's,
dvander@541
   312
		// even though the standard says you can. The 32-bit compiler lets you
dvander@541
   313
		// static_cast through an int, but the DOS compiler doesn't.
dvander@541
   314
		bound_func = horrible_cast<GenericMemFuncType>(function_to_bind);
dvander@541
   315
#else
dvander@541
   316
        bound_func = reinterpret_cast<GenericMemFuncType>(function_to_bind);
dvander@541
   317
#endif
dvander@541
   318
        return reinterpret_cast<GenericClass *>(pthis);
dvander@541
   319
	}
dvander@541
   320
};
dvander@541
   321
dvander@541
   322
////////////////////////////////////////////////////////////////////////////////
dvander@541
   323
//						Fast Delegates, part 1b:
dvander@541
   324
//
dvander@541
   325
//					Workarounds for Microsoft and Intel
dvander@541
   326
//
dvander@541
   327
////////////////////////////////////////////////////////////////////////////////
dvander@541
   328
dvander@541
   329
dvander@541
   330
// Compilers with member function pointers which violate the standard (MSVC, Intel, Codeplay),
dvander@541
   331
// need to be treated as a special case.
dvander@541
   332
#ifdef FASTDLGT_MICROSOFT_MFP
dvander@541
   333
dvander@541
   334
// We use unions to perform horrible_casts. I would like to use #pragma pack(push, 1)
dvander@541
   335
// at the start of each function for extra safety, but VC6 seems to ICE
dvander@541
   336
// intermittently if you do this inside a template.
dvander@541
   337
dvander@541
   338
// __multiple_inheritance classes go here
dvander@541
   339
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
dvander@541
   340
template<>
dvander@541
   341
struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) >  {
dvander@541
   342
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   343
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   344
		GenericMemFuncType &bound_func) {
dvander@541
   345
		// We need to use a horrible_cast to do this conversion.
dvander@541
   346
		// In MSVC, a multiple inheritance member pointer is internally defined as:
dvander@541
   347
        union {
dvander@541
   348
			XFuncType func;
dvander@541
   349
			struct {
dvander@541
   350
				GenericMemFuncType funcaddress; // points to the actual member function
dvander@541
   351
				int delta;	     // #BYTES to be added to the 'this' pointer
dvander@541
   352
			}s;
dvander@541
   353
        } u;
dvander@541
   354
		// Check that the horrible_cast will work
dvander@541
   355
		typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1];
dvander@541
   356
        u.func = function_to_bind;
dvander@541
   357
		bound_func = u.s.funcaddress;
dvander@541
   358
		return reinterpret_cast<GenericClass *>(reinterpret_cast<char *>(pthis) + u.s.delta);
dvander@541
   359
	}
dvander@541
   360
};
dvander@541
   361
dvander@541
   362
// virtual inheritance is a real nuisance. It's inefficient and complicated.
dvander@541
   363
// On MSVC and Intel, there isn't enough information in the pointer itself to
dvander@541
   364
// enable conversion to a closure pointer. Earlier versions of this code didn't
dvander@541
   365
// work for all cases, and generated a compile-time error instead.
dvander@541
   366
// But a very clever hack invented by John M. Dlugosz solves this problem.
dvander@541
   367
// My code is somewhat different to his: I have no asm code, and I make no
dvander@541
   368
// assumptions about the calling convention that is used.
dvander@541
   369
dvander@541
   370
// In VC++ and ICL, a virtual_inheritance member pointer
dvander@541
   371
// is internally defined as:
dvander@541
   372
struct MicrosoftVirtualMFP {
dvander@541
   373
	void (GenericClass::*codeptr)(); // points to the actual member function
dvander@541
   374
	int delta;		// #bytes to be added to the 'this' pointer
dvander@541
   375
	int vtable_index; // or 0 if no virtual inheritance
dvander@541
   376
};
dvander@541
   377
// The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the
dvander@541
   378
// m_codeptr member is *always* called, regardless of the values of the other
dvander@541
   379
// members. (This is *not* true for other compilers, eg GCC, which obtain the
dvander@541
   380
// function address from the vtable if a virtual function is being called).
dvander@541
   381
// Dlugosz's trick is to make the codeptr point to a probe function which
dvander@541
   382
// returns the 'this' pointer that was used.
dvander@541
   383
dvander@541
   384
// Define a generic class that uses virtual inheritance.
dvander@541
   385
// It has a trival member function that returns the value of the 'this' pointer.
dvander@541
   386
struct GenericVirtualClass : virtual public GenericClass
dvander@541
   387
{
dvander@541
   388
	typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)();
dvander@541
   389
	GenericVirtualClass * GetThis() { return this; }
dvander@541
   390
};
dvander@541
   391
dvander@541
   392
// __virtual_inheritance classes go here
dvander@541
   393
template <>
dvander@541
   394
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 2*sizeof(int) >
dvander@541
   395
{
dvander@541
   396
dvander@541
   397
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   398
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   399
		GenericMemFuncType &bound_func) {
dvander@541
   400
		union {
dvander@541
   401
			XFuncType func;
dvander@541
   402
			GenericClass* (X::*ProbeFunc)();
dvander@541
   403
			MicrosoftVirtualMFP s;
dvander@541
   404
		} u;
dvander@541
   405
		u.func = function_to_bind;
dvander@541
   406
		bound_func = reinterpret_cast<GenericMemFuncType>(u.s.codeptr);
dvander@541
   407
		union {
dvander@541
   408
			GenericVirtualClass::ProbePtrType virtfunc;
dvander@541
   409
			MicrosoftVirtualMFP s;
dvander@541
   410
		} u2;
dvander@541
   411
		// Check that the horrible_cast<>s will work
dvander@541
   412
		typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)
dvander@541
   413
			&& sizeof(function_to_bind)==sizeof(u.ProbeFunc)
dvander@541
   414
			&& sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1];
dvander@541
   415
   // Unfortunately, taking the address of a MF prevents it from being inlined, so
dvander@541
   416
   // this next line can't be completely optimised away by the compiler.
dvander@541
   417
		u2.virtfunc = &GenericVirtualClass::GetThis;
dvander@541
   418
		u.s.codeptr = u2.s.codeptr;
dvander@541
   419
		return (pthis->*u.ProbeFunc)();
dvander@541
   420
	}
dvander@541
   421
};
dvander@541
   422
dvander@541
   423
#if (_MSC_VER <1300)
dvander@541
   424
dvander@541
   425
// Nasty hack for Microsoft Visual C++ 6.0
dvander@541
   426
// unknown_inheritance classes go here
dvander@541
   427
// There is a compiler bug in MSVC6 which generates incorrect code in this case!!
dvander@541
   428
template <>
dvander@541
   429
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
dvander@541
   430
{
dvander@541
   431
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   432
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   433
		GenericMemFuncType &bound_func) {
dvander@541
   434
		// There is an apalling but obscure compiler bug in MSVC6 and earlier:
dvander@541
   435
		// vtable_index and 'vtordisp' are always set to 0 in the
dvander@541
   436
		// unknown_inheritance case!
dvander@541
   437
		// This means that an incorrect function could be called!!!
dvander@541
   438
		// Compiling with the /vmg option leads to potentially incorrect code.
dvander@541
   439
		// This is probably the reason that the IDE has a user interface for specifying
dvander@541
   440
		// the /vmg option, but it is disabled -  you can only specify /vmg on
dvander@541
   441
		// the command line. In VC1.5 and earlier, the compiler would ICE if it ever
dvander@541
   442
		// encountered this situation.
dvander@541
   443
		// It is OK to use the /vmg option if /vmm or /vms is specified.
dvander@541
   444
dvander@541
   445
		// Fortunately, the wrong function is only called in very obscure cases.
dvander@541
   446
		// It only occurs when a derived class overrides a virtual function declared
dvander@541
   447
		// in a virtual base class, and the member function
dvander@541
   448
		// points to the *Derived* version of that function. The problem can be
dvander@541
   449
		// completely averted in 100% of cases by using the *Base class* for the
dvander@541
   450
		// member fpointer. Ie, if you use the base class as an interface, you'll
dvander@541
   451
		// stay out of trouble.
dvander@541
   452
		// Occasionally, you might want to point directly to a derived class function
dvander@541
   453
		// that isn't an override of a base class. In this case, both vtable_index
dvander@541
   454
		// and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated.
dvander@541
   455
		// We can generate correct code in this case. To prevent an incorrect call from
dvander@541
   456
		// ever being made, on MSVC6 we generate a warning, and call a function to
dvander@541
   457
		// make the program crash instantly.
dvander@541
   458
		typedef char ERROR_VC6CompilerBug[-100];
dvander@541
   459
		return 0;
dvander@541
   460
	}
dvander@541
   461
};
dvander@541
   462
dvander@541
   463
dvander@541
   464
#else
dvander@541
   465
dvander@541
   466
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
dvander@541
   467
// unknown_inheritance classes go here
dvander@541
   468
// This is probably the ugliest bit of code I've ever written. Look at the casts!
dvander@541
   469
// There is a compiler bug in MSVC6 which prevents it from using this code.
dvander@541
   470
template <>
dvander@541
   471
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
dvander@541
   472
{
dvander@541
   473
	template <class X, class XFuncType, class GenericMemFuncType>
dvander@541
   474
	inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
dvander@541
   475
			GenericMemFuncType &bound_func) {
dvander@541
   476
		// The member function pointer is 16 bytes long. We can't use a normal cast, but
dvander@541
   477
		// we can use a union to do the conversion.
dvander@541
   478
		union {
dvander@541
   479
			XFuncType func;
dvander@541
   480
			// In VC++ and ICL, an unknown_inheritance member pointer
dvander@541
   481
			// is internally defined as:
dvander@541
   482
			struct {
dvander@541
   483
				GenericMemFuncType m_funcaddress; // points to the actual member function
dvander@541
   484
				int delta;		// #bytes to be added to the 'this' pointer
dvander@541
   485
				int vtordisp;		// #bytes to add to 'this' to find the vtable
dvander@541
   486
				int vtable_index; // or 0 if no virtual inheritance
dvander@541
   487
			} s;
dvander@541
   488
		} u;
dvander@541
   489
		// Check that the horrible_cast will work
dvander@541
   490
		typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1];
dvander@541
   491
		u.func = function_to_bind;
dvander@541
   492
		bound_func = u.s.funcaddress;
dvander@541
   493
		int virtual_delta = 0;
dvander@541
   494
		if (u.s.vtable_index) { // Virtual inheritance is used
dvander@541
   495
			// First, get to the vtable.
dvander@541
   496
			// It is 'vtordisp' bytes from the start of the class.
dvander@541
   497
			const int * vtable = *reinterpret_cast<const int *const*>(
dvander@541
   498
				reinterpret_cast<const char *>(pthis) + u.s.vtordisp );
dvander@541
   499
dvander@541
   500
			// 'vtable_index' tells us where in the table we should be looking.
dvander@541
   501
			virtual_delta = u.s.vtordisp + *reinterpret_cast<const int *>(
dvander@541
   502
				reinterpret_cast<const char *>(vtable) + u.s.vtable_index);
dvander@541
   503
		}
dvander@541
   504
		// The int at 'virtual_delta' gives us the amount to add to 'this'.
dvander@541
   505
        // Finally we can add the three components together. Phew!
dvander@541
   506
        return reinterpret_cast<GenericClass *>(
dvander@541
   507
			reinterpret_cast<char *>(pthis) + u.s.delta + virtual_delta);
dvander@541
   508
	};
dvander@541
   509
};
dvander@541
   510
#endif // MSVC 7 and greater
dvander@541
   511
dvander@541
   512
#endif // MS/Intel hacks
dvander@541
   513
dvander@541
   514
}  // namespace detail
dvander@541
   515
dvander@541
   516
////////////////////////////////////////////////////////////////////////////////
dvander@541
   517
//						Fast Delegates, part 2:
dvander@541
   518
//
dvander@541
   519
//	Define the delegate storage, and cope with static functions
dvander@541
   520
//
dvander@541
   521
////////////////////////////////////////////////////////////////////////////////
dvander@541
   522
dvander@541
   523
// DelegateMemento -- an opaque structure which can hold an arbitary delegate.
dvander@541
   524
// It knows nothing about the calling convention or number of arguments used by
dvander@541
   525
// the function pointed to.
dvander@541
   526
// It supplies comparison operators so that it can be stored in STL collections.
dvander@541
   527
// It cannot be set to anything other than null, nor invoked directly:
dvander@541
   528
//   it must be converted to a specific delegate.
dvander@541
   529
dvander@541
   530
// Implementation:
dvander@541
   531
// There are two possible implementations: the Safe method and the Evil method.
dvander@541
   532
//				DelegateMemento - Safe version
dvander@541
   533
//
dvander@541
   534
// This implementation is standard-compliant, but a bit tricky.
dvander@541
   535
// A static function pointer is stored inside the class.
dvander@541
   536
// Here are the valid values:
dvander@541
   537
// +-- Static pointer --+--pThis --+-- pMemFunc-+-- Meaning------+
dvander@541
   538
// |   0				|  0       |   0        | Empty          |
dvander@541
   539
// |   !=0              |(dontcare)|  Invoker   | Static function|
dvander@541
   540
// |   0                |  !=0     |  !=0*      | Method call    |
dvander@541
   541
// +--------------------+----------+------------+----------------+
dvander@541
   542
//  * For Metrowerks, this can be 0. (first virtual function in a 
dvander@541
   543
//       single_inheritance class).
dvander@541
   544
// When stored stored inside a specific delegate, the 'dontcare' entries are replaced
dvander@541
   545
// with a reference to the delegate itself. This complicates the = and == operators
dvander@541
   546
// for the delegate class.
dvander@541
   547
dvander@541
   548
//				DelegateMemento - Evil version
dvander@541
   549
//
dvander@541
   550
// For compilers where data pointers are at least as big as code pointers, it is
dvander@541
   551
// possible to store the function pointer in the this pointer, using another
dvander@541
   552
// horrible_cast. In this case the DelegateMemento implementation is simple:
dvander@541
   553
// +--pThis --+-- pMemFunc-+-- Meaning---------------------+
dvander@541
   554
// |    0     |  0         | Empty                         |
dvander@541
   555
// |  !=0     |  !=0*      | Static function or method call|
dvander@541
   556
// +----------+------------+-------------------------------+
dvander@541
   557
//  * For Metrowerks, this can be 0. (first virtual function in a 
dvander@541
   558
//       single_inheritance class).
dvander@541
   559
// Note that the Sun C++ and MSVC documentation explicitly state that they 
dvander@541
   560
// support static_cast between void * and function pointers.
dvander@541
   561
dvander@541
   562
class DelegateMemento {
dvander@541
   563
protected:
dvander@541
   564
	// the data is protected, not private, because many
dvander@541
   565
	// compilers have problems with template friends.
dvander@541
   566
	typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP.
dvander@541
   567
	detail::GenericClass *m_pthis;
dvander@541
   568
	GenericMemFuncType m_pFunction;
dvander@541
   569
dvander@541
   570
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   571
	typedef void (*GenericFuncPtr)(); // arbitrary code pointer
dvander@541
   572
	GenericFuncPtr m_pStaticFunction;
dvander@541
   573
#endif
dvander@541
   574
dvander@541
   575
public:
dvander@541
   576
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   577
	DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {};
dvander@541
   578
	void clear() {
dvander@541
   579
		m_pthis=0; m_pFunction=0; m_pStaticFunction=0;
dvander@541
   580
	}
dvander@541
   581
#else
dvander@541
   582
	DelegateMemento() : m_pthis(0), m_pFunction(0) {};
dvander@541
   583
	void clear() {	m_pthis=0; m_pFunction=0;	}
dvander@541
   584
#endif
dvander@541
   585
public:
dvander@541
   586
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   587
	inline bool IsEqual (const DelegateMemento &x) const{
dvander@541
   588
	    // We have to cope with the static function pointers as a special case
dvander@541
   589
		if (m_pFunction!=x.m_pFunction) return false;
dvander@541
   590
		// the static function ptrs must either both be equal, or both be 0.
dvander@541
   591
		if (m_pStaticFunction!=x.m_pStaticFunction) return false;
dvander@541
   592
		if (m_pStaticFunction!=0) return m_pthis==x.m_pthis;
dvander@541
   593
		else return true;
dvander@541
   594
	}
dvander@541
   595
#else // Evil Method
dvander@541
   596
	inline bool IsEqual (const DelegateMemento &x) const{
dvander@541
   597
		return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction;
dvander@541
   598
	}
dvander@541
   599
#endif
dvander@541
   600
	// Provide a strict weak ordering for DelegateMementos.
dvander@541
   601
	inline bool IsLess(const DelegateMemento &right) const {
dvander@541
   602
		// deal with static function pointers first
dvander@541
   603
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   604
		if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0)
dvander@541
   605
				return m_pStaticFunction < right.m_pStaticFunction;
dvander@541
   606
#endif
dvander@541
   607
		if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis;
dvander@541
   608
	// There are no ordering operators for member function pointers,
dvander@541
   609
	// but we can fake one by comparing each byte. The resulting ordering is
dvander@541
   610
	// arbitrary (and compiler-dependent), but it permits storage in ordered STL containers.
dvander@541
   611
		return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0;
dvander@541
   612
dvander@541
   613
	}
dvander@541
   614
	// BUGFIX (Mar 2005):
dvander@541
   615
	// We can't just compare m_pFunction because on Metrowerks,
dvander@541
   616
	// m_pFunction can be zero even if the delegate is not empty!
dvander@541
   617
	inline bool operator ! () const		// Is it bound to anything?
dvander@541
   618
	{ return m_pthis==0 && m_pFunction==0; }
dvander@541
   619
	inline bool empty() const		// Is it bound to anything?
dvander@541
   620
	{ return m_pthis==0 && m_pFunction==0; }
dvander@541
   621
public:
dvander@541
   622
	DelegateMemento & operator = (const DelegateMemento &right)  {
dvander@541
   623
		SetMementoFrom(right);
dvander@541
   624
		return *this;
dvander@541
   625
	}
dvander@541
   626
	inline bool operator <(const DelegateMemento &right) {
dvander@541
   627
		return IsLess(right);
dvander@541
   628
	}
dvander@541
   629
	inline bool operator >(const DelegateMemento &right) {
dvander@541
   630
		return right.IsLess(*this);
dvander@541
   631
	}
dvander@541
   632
	DelegateMemento (const DelegateMemento &right)  :
dvander@541
   633
		m_pthis(right.m_pthis), m_pFunction(right.m_pFunction)
dvander@541
   634
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   635
		, m_pStaticFunction (right.m_pStaticFunction)
dvander@541
   636
#endif
dvander@541
   637
		{}
dvander@541
   638
protected:
dvander@541
   639
	void SetMementoFrom(const DelegateMemento &right)  {
dvander@541
   640
		m_pFunction = right.m_pFunction;
dvander@541
   641
		m_pthis = right.m_pthis;
dvander@541
   642
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   643
		m_pStaticFunction = right.m_pStaticFunction;
dvander@541
   644
#endif
dvander@541
   645
	}
dvander@541
   646
};
dvander@541
   647
dvander@541
   648
dvander@541
   649
//						ClosurePtr<>
dvander@541
   650
//
dvander@541
   651
// A private wrapper class that adds function signatures to DelegateMemento.
dvander@541
   652
// It's the class that does most of the actual work.
dvander@541
   653
// The signatures are specified by:
dvander@541
   654
// GenericMemFunc: must be a type of GenericClass member function pointer.
dvander@541
   655
// StaticFuncPtr:  must be a type of function pointer with the same signature
dvander@541
   656
//                 as GenericMemFunc.
dvander@541
   657
// UnvoidStaticFuncPtr: is the same as StaticFuncPtr, except on VC6
dvander@541
   658
//                 where it never returns void (returns DefaultVoid instead).
dvander@541
   659
dvander@541
   660
// An outer class, FastDelegateN<>, handles the invoking and creates the
dvander@541
   661
// necessary typedefs.
dvander@541
   662
// This class does everything else.
dvander@541
   663
dvander@541
   664
namespace detail {
dvander@541
   665
dvander@541
   666
template < class GenericMemFunc, class StaticFuncPtr, class UnvoidStaticFuncPtr>
dvander@541
   667
class ClosurePtr : public DelegateMemento {
dvander@541
   668
public:
dvander@541
   669
	// These functions are for setting the delegate to a member function.
dvander@541
   670
dvander@541
   671
	// Here's the clever bit: we convert an arbitrary member function into a
dvander@541
   672
	// standard form. XMemFunc should be a member function of class X, but I can't
dvander@541
   673
	// enforce that here. It needs to be enforced by the wrapper class.
dvander@541
   674
	template < class X, class XMemFunc >
dvander@541
   675
	inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) {
dvander@541
   676
		m_pthis = SimplifyMemFunc< sizeof(function_to_bind) >
dvander@541
   677
			::Convert(pthis, function_to_bind, m_pFunction);
dvander@541
   678
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   679
		m_pStaticFunction = 0;
dvander@541
   680
#endif
dvander@541
   681
	}
dvander@541
   682
	// For const member functions, we only need a const class pointer.
dvander@541
   683
	// Since we know that the member function is const, it's safe to
dvander@541
   684
	// remove the const qualifier from the 'this' pointer with a const_cast.
dvander@541
   685
	// VC6 has problems if we just overload 'bindmemfunc', so we give it a different name.
dvander@541
   686
	template < class X, class XMemFunc>
dvander@541
   687
	inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) {
dvander@541
   688
		m_pthis= SimplifyMemFunc< sizeof(function_to_bind) >
dvander@541
   689
			::Convert(const_cast<X*>(pthis), function_to_bind, m_pFunction);
dvander@541
   690
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   691
		m_pStaticFunction = 0;
dvander@541
   692
#endif
dvander@541
   693
	}
dvander@541
   694
#ifdef FASTDELEGATE_GCC_BUG_8271	// At present, GCC doesn't recognize constness of MFPs in templates
dvander@541
   695
	template < class X, class XMemFunc>
dvander@541
   696
	inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) {
dvander@541
   697
		bindconstmemfunc(pthis, function_to_bind);
dvander@541
   698
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   699
		m_pStaticFunction = 0;
dvander@541
   700
#endif
dvander@541
   701
	}
dvander@541
   702
#endif
dvander@541
   703
	// These functions are required for invoking the stored function
dvander@541
   704
	inline GenericClass *GetClosureThis() const { return m_pthis; }
dvander@541
   705
	inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast<GenericMemFunc>(m_pFunction); }
dvander@541
   706
dvander@541
   707
// There are a few ways of dealing with static function pointers.
dvander@541
   708
// There's a standard-compliant, but tricky method.
dvander@541
   709
// There's also a straightforward hack, that won't work on DOS compilers using the
dvander@541
   710
// medium memory model. It's so evil that I can't recommend it, but I've
dvander@541
   711
// implemented it anyway because it produces very nice asm code.
dvander@541
   712
dvander@541
   713
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   714
dvander@541
   715
//				ClosurePtr<> - Safe version
dvander@541
   716
//
dvander@541
   717
// This implementation is standard-compliant, but a bit tricky.
dvander@541
   718
// I store the function pointer inside the class, and the delegate then
dvander@541
   719
// points to itself. Whenever the delegate is copied, these self-references
dvander@541
   720
// must be transformed, and this complicates the = and == operators.
dvander@541
   721
public:
dvander@541
   722
	// The next two functions are for operator ==, =, and the copy constructor.
dvander@541
   723
	// We may need to convert the m_pthis pointers, so that
dvander@541
   724
	// they remain as self-references.
dvander@541
   725
	template< class DerivedClass >
dvander@541
   726
	inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) {
dvander@541
   727
		SetMementoFrom(x);
dvander@541
   728
		if (m_pStaticFunction!=0) {
dvander@541
   729
			// transform self references...
dvander@541
   730
			m_pthis=reinterpret_cast<GenericClass *>(pParent);
dvander@541
   731
		}
dvander@541
   732
	}
dvander@541
   733
	// For static functions, the 'static_function_invoker' class in the parent
dvander@541
   734
	// will be called. The parent then needs to call GetStaticFunction() to find out
dvander@541
   735
	// the actual function to invoke.
dvander@541
   736
	template < class DerivedClass, class ParentInvokerSig >
dvander@541
   737
	inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
dvander@541
   738
				StaticFuncPtr function_to_bind ) {
dvander@541
   739
		if (function_to_bind==0) { // cope with assignment to 0
dvander@541
   740
			m_pFunction=0;
dvander@541
   741
		} else {
dvander@541
   742
			bindmemfunc(pParent, static_function_invoker);
dvander@541
   743
        }
dvander@541
   744
		m_pStaticFunction=reinterpret_cast<GenericFuncPtr>(function_to_bind);
dvander@541
   745
	}
dvander@541
   746
	inline UnvoidStaticFuncPtr GetStaticFunction() const {
dvander@541
   747
		return reinterpret_cast<UnvoidStaticFuncPtr>(m_pStaticFunction);
dvander@541
   748
	}
dvander@541
   749
#else
dvander@541
   750
dvander@541
   751
//				ClosurePtr<> - Evil version
dvander@541
   752
//
dvander@541
   753
// For compilers where data pointers are at least as big as code pointers, it is
dvander@541
   754
// possible to store the function pointer in the this pointer, using another
dvander@541
   755
// horrible_cast. Invocation isn't any faster, but it saves 4 bytes, and
dvander@541
   756
// speeds up comparison and assignment. If C++ provided direct language support
dvander@541
   757
// for delegates, they would produce asm code that was almost identical to this.
dvander@541
   758
// Note that the Sun C++ and MSVC documentation explicitly state that they
dvander@541
   759
// support static_cast between void * and function pointers.
dvander@541
   760
dvander@541
   761
	template< class DerivedClass >
dvander@541
   762
	inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) {
dvander@541
   763
		SetMementoFrom(right);
dvander@541
   764
	}
dvander@541
   765
	// For static functions, the 'static_function_invoker' class in the parent
dvander@541
   766
	// will be called. The parent then needs to call GetStaticFunction() to find out
dvander@541
   767
	// the actual function to invoke.
dvander@541
   768
	// ******** EVIL, EVIL CODE! *******
dvander@541
   769
	template < 	class DerivedClass, class ParentInvokerSig>
dvander@541
   770
	inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
dvander@541
   771
				StaticFuncPtr function_to_bind) {
dvander@541
   772
		if (function_to_bind==0) { // cope with assignment to 0
dvander@541
   773
			m_pFunction=0;
dvander@541
   774
		} else { 
dvander@541
   775
		   // We'll be ignoring the 'this' pointer, but we need to make sure we pass
dvander@541
   776
		   // a valid value to bindmemfunc().
dvander@541
   777
			bindmemfunc(pParent, static_function_invoker);
dvander@541
   778
        }
dvander@541
   779
dvander@541
   780
		// WARNING! Evil hack. We store the function in the 'this' pointer!
dvander@541
   781
		// Ensure that there's a compilation failure if function pointers
dvander@541
   782
		// and data pointers have different sizes.
dvander@541
   783
		// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
dvander@541
   784
		typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1];
dvander@541
   785
		m_pthis = horrible_cast<GenericClass *>(function_to_bind);
dvander@541
   786
		// MSVC, SunC++ and DMC accept the following (non-standard) code:
dvander@541
   787
//		m_pthis = static_cast<GenericClass *>(static_cast<void *>(function_to_bind));
dvander@541
   788
		// BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long
dvander@541
   789
//		m_pthis = reinterpret_cast<GenericClass *>(reinterpret_cast<long>(function_to_bind));
dvander@541
   790
	}
dvander@541
   791
	// ******** EVIL, EVIL CODE! *******
dvander@541
   792
	// This function will be called with an invalid 'this' pointer!!
dvander@541
   793
	// We're just returning the 'this' pointer, converted into
dvander@541
   794
	// a function pointer!
dvander@541
   795
	inline UnvoidStaticFuncPtr GetStaticFunction() const {
dvander@541
   796
		// Ensure that there's a compilation failure if function pointers
dvander@541
   797
		// and data pointers have different sizes.
dvander@541
   798
		// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
dvander@541
   799
		typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1];
dvander@541
   800
		return horrible_cast<UnvoidStaticFuncPtr>(this);
dvander@541
   801
	}
dvander@541
   802
#endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
dvander@541
   803
dvander@541
   804
	// Does the closure contain this static function?
dvander@541
   805
	inline bool IsEqualToStaticFuncPtr(StaticFuncPtr funcptr){
dvander@541
   806
		if (funcptr==0) return empty();
dvander@541
   807
	// For the Evil method, if it doesn't actually contain a static function, this will return an arbitrary
dvander@541
   808
	// value that is not equal to any valid function pointer.
dvander@541
   809
		else return funcptr==reinterpret_cast<StaticFuncPtr>(GetStaticFunction());
dvander@541
   810
	}
dvander@541
   811
};
dvander@541
   812
dvander@541
   813
dvander@541
   814
} // namespace detail
dvander@541
   815
dvander@541
   816
////////////////////////////////////////////////////////////////////////////////
dvander@541
   817
//						Fast Delegates, part 3:
dvander@541
   818
//
dvander@541
   819
//				Wrapper classes to ensure type safety
dvander@541
   820
//
dvander@541
   821
////////////////////////////////////////////////////////////////////////////////
dvander@541
   822
dvander@541
   823
dvander@541
   824
// Once we have the member function conversion templates, it's easy to make the
dvander@541
   825
// wrapper classes. So that they will work with as many compilers as possible,
dvander@541
   826
// the classes are of the form
dvander@541
   827
//   FastDelegate3<int, char *, double>
dvander@541
   828
// They can cope with any combination of parameters. The max number of parameters
dvander@541
   829
// allowed is 8, but it is trivial to increase this limit.
dvander@541
   830
// Note that we need to treat const member functions seperately.
dvander@541
   831
// All this class does is to enforce type safety, and invoke the delegate with
dvander@541
   832
// the correct list of parameters.
dvander@541
   833
dvander@541
   834
// Because of the weird rule about the class of derived member function pointers,
dvander@541
   835
// you sometimes need to apply a downcast to the 'this' pointer.
dvander@541
   836
// This is the reason for the use of "implicit_cast<X*>(pthis)" in the code below.
dvander@541
   837
// If CDerivedClass is derived from CBaseClass, but doesn't override SimpleVirtualFunction,
dvander@541
   838
// without this trick you'd need to write:
dvander@541
   839
//		MyDelegate(static_cast<CBaseClass *>(&d), &CDerivedClass::SimpleVirtualFunction);
dvander@541
   840
// but with the trick you can write
dvander@541
   841
//		MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction);
dvander@541
   842
dvander@541
   843
// RetType is the type the compiler uses in compiling the template. For VC6,
dvander@541
   844
// it cannot be void. DesiredRetType is the real type which is returned from
dvander@541
   845
// all of the functions. It can be void.
dvander@541
   846
dvander@541
   847
// Implicit conversion to "bool" is achieved using the safe_bool idiom,
dvander@541
   848
// using member data pointers (MDP). This allows "if (dg)..." syntax
dvander@541
   849
// Because some compilers (eg codeplay) don't have a unique value for a zero
dvander@541
   850
// MDP, an extra padding member is added to the SafeBool struct.
dvander@541
   851
// Some compilers (eg VC6) won't implicitly convert from 0 to an MDP, so
dvander@541
   852
// in that case the static function constructor is not made explicit; this
dvander@541
   853
// allows "if (dg==0) ..." to compile.
dvander@541
   854
dvander@541
   855
@VARARGS
dvander@541
   856
template<@CLASSARGS, class RetType=detail::DefaultVoid>
dvander@541
   857
class FastDelegate@NUM {
dvander@541
   858
private:
dvander@541
   859
	typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
dvander@541
   860
	typedef DesiredRetType (*StaticFunctionPtr)(@FUNCARGS);
dvander@541
   861
	typedef RetType (*UnvoidStaticFunctionPtr)(@FUNCARGS);
dvander@541
   862
	typedef RetType (detail::GenericClass::*GenericMemFn)(@FUNCARGS);
dvander@541
   863
	typedef detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> ClosureType;
dvander@541
   864
	ClosureType m_Closure;
dvander@541
   865
public:
dvander@541
   866
	// Typedefs to aid generic programming
dvander@541
   867
	typedef FastDelegate@NUM type;
dvander@541
   868
dvander@541
   869
	// Construction and comparison functions
dvander@541
   870
	FastDelegate@NUM() { clear(); }
dvander@541
   871
	FastDelegate@NUM(const FastDelegate@NUM &x) {
dvander@541
   872
		m_Closure.CopyFrom(this, x.m_Closure); }
dvander@541
   873
	void operator = (const FastDelegate@NUM &x)  {
dvander@541
   874
		m_Closure.CopyFrom(this, x.m_Closure); }
dvander@541
   875
	bool operator ==(const FastDelegate@NUM &x) const {
dvander@541
   876
		return m_Closure.IsEqual(x.m_Closure);	}
dvander@541
   877
	bool operator !=(const FastDelegate@NUM &x) const {
dvander@541
   878
		return !m_Closure.IsEqual(x.m_Closure); }
dvander@541
   879
	bool operator <(const FastDelegate@NUM &x) const {
dvander@541
   880
		return m_Closure.IsLess(x.m_Closure);	}
dvander@541
   881
	bool operator >(const FastDelegate@NUM &x) const {
dvander@541
   882
		return x.m_Closure.IsLess(m_Closure);	}
dvander@541
   883
	// Binding to non-const member functions
dvander@541
   884
	template < class X, class Y >
dvander@541
   885
	FastDelegate@NUM(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) ) {
dvander@541
   886
		m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
dvander@541
   887
	template < class X, class Y >
dvander@541
   888
	inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS)) {
dvander@541
   889
		m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind);	}
dvander@541
   890
	// Binding to const member functions.
dvander@541
   891
	template < class X, class Y >
dvander@541
   892
	FastDelegate@NUM(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
dvander@541
   893
		m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind);	}
dvander@541
   894
	template < class X, class Y >
dvander@541
   895
	inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
dvander@541
   896
		m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind);	}
dvander@541
   897
	// Static functions. We convert them into a member function call.
dvander@541
   898
	// This constructor also provides implicit conversion
dvander@541
   899
	FastDelegate@NUM(DesiredRetType (*function_to_bind)(@FUNCARGS) ) {
dvander@541
   900
		bind(function_to_bind);	}
dvander@541
   901
	// for efficiency, prevent creation of a temporary
dvander@541
   902
	void operator = (DesiredRetType (*function_to_bind)(@FUNCARGS) ) {
dvander@541
   903
		bind(function_to_bind);	}
dvander@541
   904
	inline void bind(DesiredRetType (*function_to_bind)(@FUNCARGS)) {
dvander@541
   905
		m_Closure.bindstaticfunc(this, &FastDelegate@NUM::InvokeStaticFunction,
dvander@541
   906
			function_to_bind); }
dvander@541
   907
	// Invoke the delegate
dvander@541
   908
	RetType operator() (@FUNCARGS) const {
dvander@541
   909
	return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(@INVOKEARGS); }
dvander@541
   910
	// Implicit conversion to "bool" using the safe_bool idiom
dvander@541
   911
private:
dvander@541
   912
	typedef struct SafeBoolStruct {
dvander@541
   913
		int a_data_pointer_to_this_is_0_on_buggy_compilers;
dvander@541
   914
		StaticFunctionPtr m_nonzero;
dvander@541
   915
	} UselessTypedef;
dvander@541
   916
    typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type;
dvander@541
   917
public:
dvander@541
   918
	operator unspecified_bool_type() const {
dvander@541
   919
        return empty()? 0: &SafeBoolStruct::m_nonzero;
dvander@541
   920
    }
dvander@541
   921
	// necessary to allow ==0 to work despite the safe_bool idiom
dvander@541
   922
	inline bool operator==(StaticFunctionPtr funcptr) {
dvander@541
   923
		return m_Closure.IsEqualToStaticFuncPtr(funcptr);	}
dvander@541
   924
	inline bool operator!=(StaticFunctionPtr funcptr) { 
dvander@541
   925
		return !m_Closure.IsEqualToStaticFuncPtr(funcptr);    }
dvander@541
   926
	inline bool operator ! () const	{	// Is it bound to anything?
dvander@541
   927
			return !m_Closure; }
dvander@541
   928
	inline bool empty() const	{
dvander@541
   929
			return !m_Closure; }
dvander@541
   930
	void clear() { m_Closure.clear();}
dvander@541
   931
	// Conversion to and from the DelegateMemento storage class
dvander@541
   932
	const DelegateMemento & GetMemento() { return m_Closure; }
dvander@541
   933
	void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
dvander@541
   934
dvander@541
   935
private:	// Invoker for static functions
dvander@541
   936
	RetType InvokeStaticFunction(@FUNCARGS) const {
dvander@541
   937
	return (*(m_Closure.GetStaticFunction()))(@INVOKEARGS); }
dvander@541
   938
};
dvander@541
   939
dvander@541
   940
@ENDVAR
dvander@541
   941
dvander@541
   942
////////////////////////////////////////////////////////////////////////////////
dvander@541
   943
//						Fast Delegates, part 4:
dvander@541
   944
//
dvander@541
   945
//				FastDelegate<> class (Original author: Jody Hagins)
dvander@541
   946
//	Allows boost::function style syntax like:
dvander@541
   947
//			FastDelegate< double (int, long) >
dvander@541
   948
// instead of:
dvander@541
   949
//			FastDelegate2< int, long, double >
dvander@541
   950
//
dvander@541
   951
////////////////////////////////////////////////////////////////////////////////
dvander@541
   952
dvander@541
   953
#ifdef FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
   954
dvander@541
   955
// Declare FastDelegate as a class template.  It will be specialized
dvander@541
   956
// later for all number of arguments.
dvander@541
   957
template <typename Signature>
dvander@541
   958
class FastDelegate;
dvander@541
   959
dvander@541
   960
@VARARGS
dvander@541
   961
// Specialization to allow use of
dvander@541
   962
// FastDelegate< R ( @SELARGS ) >
dvander@541
   963
// instead of
dvander@541
   964
// FastDelegate@NUM < @SELARGS, R >
dvander@541
   965
template<typename R, @CLASSARGS>
dvander@541
   966
class FastDelegate< R ( @SELARGS ) >
dvander@541
   967
  // Inherit from FastDelegate@NUM so that it can be treated just like a FastDelegate@NUM
dvander@541
   968
  : public FastDelegate@NUM < @SELARGS, R >
dvander@541
   969
{
dvander@541
   970
public:
dvander@541
   971
  // Make using the base type a bit easier via typedef.
dvander@541
   972
  typedef FastDelegate@NUM < @SELARGS, R > BaseType;
dvander@541
   973
dvander@541
   974
  // Allow users access to the specific type of this delegate.
dvander@541
   975
  typedef FastDelegate SelfType;
dvander@541
   976
dvander@541
   977
  // Mimic the base class constructors.
dvander@541
   978
  FastDelegate() : BaseType() { }
dvander@541
   979
dvander@541
   980
  template < class X, class Y >
dvander@541
   981
  FastDelegate(Y * pthis,
dvander@541
   982
    R (X::* function_to_bind)( @FUNCARGS ))
dvander@541
   983
    : BaseType(pthis, function_to_bind)  { }
dvander@541
   984
dvander@541
   985
  template < class X, class Y >
dvander@541
   986
  FastDelegate(const Y *pthis,
dvander@541
   987
      R (X::* function_to_bind)( @FUNCARGS ) const)
dvander@541
   988
    : BaseType(pthis, function_to_bind)
dvander@541
   989
  {  }
dvander@541
   990
dvander@541
   991
  FastDelegate(R (*function_to_bind)( @FUNCARGS ))
dvander@541
   992
    : BaseType(function_to_bind)  { }
dvander@541
   993
  void operator = (const BaseType &x)  {
dvander@541
   994
		*static_cast<BaseType*>(this) = x; }
dvander@541
   995
};
dvander@541
   996
dvander@541
   997
@ENDVAR
dvander@541
   998
dvander@541
   999
#endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
dvander@541
  1000
dvander@541
  1001
////////////////////////////////////////////////////////////////////////////////
dvander@541
  1002
//						Fast Delegates, part 5:
dvander@541
  1003
//
dvander@541
  1004
//				MakeDelegate() helper function
dvander@541
  1005
//
dvander@541
  1006
//			MakeDelegate(&x, &X::func) returns a fastdelegate of the type
dvander@541
  1007
//			necessary for calling x.func() with the correct number of arguments.
dvander@541
  1008
//			This makes it possible to eliminate many typedefs from user code.
dvander@541
  1009
//
dvander@541
  1010
////////////////////////////////////////////////////////////////////////////////
dvander@541
  1011
dvander@541
  1012
// Also declare overloads of a MakeDelegate() global function to
dvander@541
  1013
// reduce the need for typedefs.
dvander@541
  1014
// We need seperate overloads for const and non-const member functions.
dvander@541
  1015
// Also, because of the weird rule about the class of derived member function pointers,
dvander@541
  1016
// implicit downcasts may need to be applied later to the 'this' pointer.
dvander@541
  1017
// That's why two classes (X and Y) appear in the definitions. Y must be implicitly
dvander@541
  1018
// castable to X.
dvander@541
  1019
dvander@541
  1020
// Workaround for VC6. VC6 needs void return types converted into DefaultVoid.
dvander@541
  1021
// GCC 3.2 and later won't compile this unless it's preceded by 'typename',
dvander@541
  1022
// but VC6 doesn't allow 'typename' in this context.
dvander@541
  1023
// So, I have to use a macro.
dvander@541
  1024
dvander@541
  1025
#ifdef FASTDLGT_VC6
dvander@541
  1026
#define FASTDLGT_RETTYPE detail::VoidToDefaultVoid<RetType>::type
dvander@541
  1027
#else
dvander@541
  1028
#define FASTDLGT_RETTYPE RetType
dvander@541
  1029
#endif
dvander@541
  1030
dvander@541
  1031
@VARARGS
dvander@541
  1032
template <class X, class Y, @CLASSARGS, class RetType>
dvander@541
  1033
FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS)) {
dvander@541
  1034
	return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
dvander@541
  1035
}
dvander@541
  1036
dvander@541
  1037
template <class X, class Y, @CLASSARGS, class RetType>
dvander@541
  1038
FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS) const) {
dvander@541
  1039
	return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
dvander@541
  1040
}
dvander@541
  1041
dvander@541
  1042
template <@CLASSARGS, class RetType>
dvander@541
  1043
FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(RetType (*func)(@FUNCARGS)) {
dvander@541
  1044
	return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(func);
dvander@541
  1045
}
dvander@541
  1046
dvander@541
  1047
@ENDVAR
dvander@541
  1048
dvander@541
  1049
 // clean up after ourselves...
dvander@541
  1050
#undef FASTDLGT_RETTYPE
dvander@541
  1051
dvander@541
  1052
} // namespace fastdelegate
dvander@541
  1053
dvander@541
  1054
#endif // !defined(FASTDELEGATE_H)