【问题标题】:Generate array using variadic macros使用可变参数宏生成数组
【发布时间】:2014-01-04 17:44:54
【问题描述】:

我想使用可变参数宏生成一个函数指针数组。这是一个例子。


预处理前:

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

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

MY_MACRO(test, a, b, c);

预处理后:

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

这可能吗?

基本上,我需要在数组扩展之前有一些东西,在数组扩展之后有一些东西,并为每个扩展的可变参数宏参数添加一个前缀。

【问题讨论】:

  • 如果您接受支持的参数数量的特定限制,这是可能的。但这也相当复杂,请参阅this Q/A 以获得一些灵感:)
  • 我认为类型应该是void(test::*fnPtrs[])()。请改用别名。
  • @DyP:我在真实代码中使用了别名 :)
  • @DanielFrey 你能发表你的评论作为答案吗?我愿意接受
  • 这不公平,除了记住一些要搜索的关键字外,我几乎没有做任何工作。如果你想接受答案,应该是@DyP,使用 Boost.Preprocessor 绝非易事,我敢肯定他做了很多工作。

标签: c++ c++11 macros variadic-macros


【解决方案1】:

使用 boost 的预处理器库(虽然在 clang++ 和可变参数 o.O 中存在问题,但在 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

【讨论】:

  • 当然,您也可以将数组定义放在宏中,然后在该宏中调用CREATE_MFPTR
猜你喜欢
  • 2022-08-19
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多