1

I want to generate an array of function pointers using a variadic macro. Here's an example.


Before preprocessing:

#define MY_MACRO(mClassName, ...) ???

struct test { 
    void a() { }
    void b() { }
    void c() { }
};

MY_MACRO(test, a, b, c);

After preprocessing:

struct test { 
    void a() { }
    void b() { }
    void c() { }
};

void(test::*)() getMemFnPtr(int mIdx) {
    static void(test::*)() fnPtrs[]{
        &test::a,
        &test::b,
        &test::c
    };
    return fnPtrs[mIdx];
}

Is this possible?

Basically, I need to have something before the array expansion, something after the array expansion, and add a prefix to every expanded variadic macro argument.

4

1 回答 1

3

使用 boost 的预处理器库(虽然在 clang++ 和可变参数 oO 上存在问题,但在 g++ 中可以正常工作):

#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>

#define CREATE_MFPTR(s, data, elem) \
    & BOOST_PP_EXPAND(data) :: BOOST_PP_EXPAND(elem)

#define CREATE_MFPTRS(class_name, ...)                                  \
    BOOST_PP_SEQ_ENUM(                                                  \
        BOOST_PP_SEQ_TRANSFORM(CREATE_MFPTR,                            \
                               class_name,                              \
                               BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))   \
    )                                                                   // end



struct test
{
    void a();
    void b();
    void c();
    void d();
};

using MFPtr = void (test::*)();
MFPtr arr[] = {
    CREATE_MFPTRS(test, a,b,c,d)
};

int main() {}

CREATE_MFPTRS(test, a,b,c,d)产量_

& test :: a, & test :: b, & test :: c, & test :: d
于 2014-01-04T19:47:52.343 回答