【问题标题】:How to process __VA_ARGS__ in C++ preprocessing?如何在 C++ 预处理中处理 __VA_ARGS__?
【发布时间】:2020-12-14 15:51:57
【问题描述】:
#define INITIALIZE_INT_ARRAY(elem_type, array_name,...) \
    elem_type array_name[] = { __VA_ARGS__ }; \ 

INITIALIZE_INT_ARRAY(int, arr, 1, 2, 3, 4, 5)
// will expand to
int arr[] = {1, 2, 3, 4. 5};

现在我想支持__VA_ARGS__ 中的元组,如果它是一个元组,我将简单地获取元组的第一个元素。

INITIALIZE_INT_ARRAY(int, arr, 1, (2, hello), (3, world), (4, X), 5)
// will still expand to
int arr[] = {1, 2, 3, 4, 5}

如何更改我的INITIALIZE_INT_ARRAY

【问题讨论】:

  • 我正在添加 c++ 标签,以使这个问题能够吸引更多人。

标签: c++ c-preprocessor boost-preprocessor


【解决方案1】:

一般来说,在预处理器中迭代逗号分隔的列表需要编写 O(n) 样板宏。您可以自己编写或从 Boost.Preprocessor 获取它们,或者...

您可以对列表使用不同的语法:FOO(int, arr, (1)(2, hello)(3, world)(4, X)(5))

那么宏可以这样写,不用样板:

#define FOO(type_, name_, seq_) \
    type_ name_[] = { FOO_END( FOO_LOOP_A seq_ ) }; \
    
#define FOO_END(...) FOO_END_(__VA_ARGS__)
#define FOO_END_(...) __VA_ARGS__##_END
    
#define FOO_LOOP_A(...) FOO_LOOP_BODY(__VA_ARGS__,) FOO_LOOP_B
#define FOO_LOOP_B(...) FOO_LOOP_BODY(__VA_ARGS__,) FOO_LOOP_A
#define FOO_LOOP_A_END
#define FOO_LOOP_B_END

#define FOO_LOOP_BODY(x, ...) x,

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2014-08-02
    • 2010-09-07
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多