如何在C ++预处理中处理__VA_ARGS__?

问题描述

<?PHP wp_nav_menu( array(
            'theme_location'        => 'primary',)); ?>

现在,我想在#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,4. 5}; 支持元组,并且如果它是一个元组,它将仅采用元组的第一个元素。

__VA_ARGS__

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

解决方法

通常,在预处理器中的逗号分隔列表上进行迭代需要编写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,