开发者

Help with macro functions

Given many inline functions with identical signatures. All functions are small and performance critical.

int inline f1(int);
int inline f2(int);
...
int inline f5(int);

I need to write high level functions to automate certain tasks - one high level function per each inline function. n-th high level function uses only n-th low level function, otherwise all high level functions are identical.

int F_n(int x) {
    int y;
    // use n-th low level function to compute y from x
    // for example
    y = x*f_n(x);

    return y;
}

I could use function pointers for call back, but I think it will prevent inclining and the performance will suffer. Or I could just copy&paster and manually fix function names.

Is there a way to do it with macros? A macro that can generates high level functions automatically?

#define GEN_FUNC( HIGH_LEVEL_FUNC, LOW_LEVEL_FUNC ) \
???????               \
???????               \

GEN_FUNC(F1, f1); // generate F1
GEN_FUNC(F2, f2); // generate F2
.........
GEN_FUNC(F_N, f_N); // generate F_N

Is it possible?

Thanks.

P.S. I could us开发者_StackOverflow中文版e function objects, but it should work in C too.


Why not use templates?

template <int N>
int inline f(int);

template <>
int inline f<1>(int);

template <>
int inline f<2>(int);

template <>
int inline f<3>(int);

...

template <int N>
int F(int x)
{
    int y;
    y = x * f<N>(x);
    return y;
}

Edit: If it should work in C, use a macro like this:

#define GENERATE_FUNCTION(n) \
    int F_ ## n(int x) {     \
        int y;               \
        y = x*f_ ## n(x);    \
        return y;            \
    }

And using BOOST_PP_REPEAT:

#define GENERATE_FUNCTION_STEP(z, n, unused) GENERATE_FUNCTION(n)

BOOST_PP_REPEAT(N, GENERATE_FUNCTION_STEP, ~)


I've trouble to see the difficulty:

#define GEN_FUNC( HIGH_LEVEL_FUNC, LOW_LEVEL_FUNC ) \
inline int HIGH_LEVEL_FUNC(int x) { \
    int y; \
    y = x*LOW_LEVEL_FUNC(x); \
    return y; \
}

or did I miss something?


You can do it easily with Boost.Preprocessor which does not require a C++ compiler. Using BOOST_PP_REPEAT you can easily generate n functions (you have to define n of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜