mercredi 5 août 2015

Using macros to generate argument list from __VA_ARGS__

Just for a little background, this isn't a trivial exercise! I'm working with Boost.Python, and to avoid a lot of ugly boilerplate code, I'm using macros to wrap functions in Python wrapper classes to optionally call a Python override for the method if it exists.

I've boiled the conundrum down to it's simplest form, here:

#include <iostream>

using namespace std;

void foo() { cout << "foo" << endl; }
void bar(char, short, int) { cout <<"bar" << endl; }

#define DEFINE_FUNCTION_WRAPPER(return_type, name, ...)\
return_type name##_wrapper(/* macro expansion */)\
{\
    return name(/* macro expansion */);\
}\

DEFINE_FUNCTION_WRAPPER(void, foo)  // works!
//DEFINE_FUNCTION_WRAPPER(void, foo, char, short, int)  // knowledge insufficient

int main() {
    foo_wrapper();
    //bar_wrapper(0, 1, 2);
}

While this obviously works for foo, my goal is to have DEFINE_FUNCTION_WRAPPER(void, foo, char, short, int) generate a function wrapper that looks like this:

void bar_wrapper(char _1, short _2, int _3)
{
    return bar(_1, _2, _3);
}

I'm looking to be pointed in the right direction on how best to tackle this, as I really would like to master this kind of macro magic.

Any help is appreciated!

NOTE: I'm compiling against MSVC C++11.

Aucun commentaire:

Enregistrer un commentaire