Irbis
Irbis

Reputation: 13369

trying to understand macro definition

I found fragments of a very odd code:

//first fragment 
bool status = fileToImage (name, size, stride, data);

//second fragment
WRAPABLE_HND (8, ScreenInterface, bool, fileToImage, CompString &, CompSize &, int &, void *&);


third fragment
#define WRAPABLE_HND(num,itype,rtype, func, ...)    \
rtype func (__VA_ARGS__);               \
void  func ## SetEnabled (itype *obj, bool enabled) \
{                           \
   functionSetEnabled (obj, num, enabled);      \
}                           \
unsigned int func ## GetCurrentIndex ()     \
{                           \
   return mCurrFunction[num];           \
}                           \
void func ## SetCurrentIndex (unsigned int index)   \
{                           \
   mCurrFunction[num] = index;          \
}

Could you explain me how does above macro definition work ?

Upvotes: 1

Views: 95

Answers (1)

It is a macro for defining a set of related functions. It declares/defines these functions:

  • Declares a function named func (4th macro parameter) returning rtype (3rd macro parameter), whose parameter types are specified by the 5th and successive macro parameters.

  • Defines a function named funcSetEnabled (where func is substituted by the macro argument) which takes a pointer to itype (2nd macro parameter) and a boolean, and forwards them to a function named functionSetEnabled(), along with one more argument num (1st macro parameter).

  • Defines a function named funcGetCurrentIndex (func substituted again) which returns the num-th element of an array named mCurrFunction.

  • Defines a function named funcSetCurrentIndex (func substituted again) which takes an index and writes it into the num-th element of the array named mCurrFunction.

In other words, it's a bit like a preprocessor-based template.

In your example, the macro is "called" with arguments 8, ScreenInterface, bool, fileToImage, CompString &, CompSize &, int &, void *&. So it will produce the following functions:

bool fileToImage(CompString &, CompSize &, int &, void *&);

void fileToImageSetEnabled(ScreenInterface *obj, bool enabled)
{
  functionSetEnabled(obj, 8, enabled);
}

unsigned int fileToImageGetCurrentIndex()
{
  return mCurrFunction[8];
}

void fileToImageSetCurrentIndex(unsigned int index)
{
  mCurrFunction[8] = index;
}

So apparently, it's something like a property-generation system: generating the prototype of a function and several helpers doing something with it.

Upvotes: 2

Related Questions