c++ - 帮助宏功能

标签 c++ c macros

给定许多具有相同签名的内联函数。所有函数都很小并且性能很关键。

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

我需要编写高级函数来自动执行某些任务 - 每个内联函数一个高级函数。第n个高级函数只使用第n个低级函数,否则所有高级函数都是相同的。

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;
}

我可以使用函数指针进行回调,但我认为它会阻止倾斜并且性能会受到影响。或者我可以只复制粘贴并手动修复函数名称。

有没有办法用宏来做到这一点?可以自动生成高级函数的宏?

#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

这可能吗?

谢谢。

附言我可以使用函数对象,但它也应该适用于 C。

最佳答案

为什么不使用模板?

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;
}

编辑:如果它应该在 C 中工作,请使用这样的宏:

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

并使用 BOOST_PP_REPEAT:

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

BOOST_PP_REPEAT(N, GENERATE_FUNCTION_STEP, ~)

关于c++ - 帮助宏功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192230/

相关文章:

c++ - 不释放内存是否可以接受

android - 如何在没有android studio的情况下在linux上开发android应用程序?

C++ 使用 constexpr 使放置新对齐的存储可初始化

c++ - 程序终止时清理 pthread 资源

c - 如何将用户空间进程切换回根网络命名空间?

c - JNI ThrowNew 什么时候会失败?

c++ - Windows 上的堆栈 - 它在哪里?

c - 如何检测类型是 C 预处理器中的指针?

macros - 旁边不需要空格的 Clojure 宏

c++ - 计算距对象起点的距离时,_ATL_PACKING 常量有什么用?