C++ preprocessor--join arguments

六眼飞鱼酱① 提交于 2020-01-17 05:38:19

问题


Is there a way to make the C++ preprocessor join arguments with a joiner token?

I've learned that I can do:

#include <boost/preprocessor/seq/cat.hpp>
#define arg1 foo
#define arg2 bar
#define arg3 baz
BOOST_PP_SEQ_CAT((arg1)(_)(arg2)(_)(arg3))

to get foo_bar_baz.

I have two questions:

  1. Is there a way to do it for without the repeated explicit joiner characters ((_)) and for an argument list of variadic length?
  2. Is it necessary to pass the arguments like so:

    (arg1)(arg2)(arg3)
    

    Can I wrap it in another macro that'll allow me to pass argument normally, i.e.?:

    arg1, arg2, arg3
    

回答1:


#define BOOST_PP_VARIADICS
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/fold_left.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>

#define OP(s, state, x) BOOST_PP_CAT(state, BOOST_PP_CAT(_, x))
#define COMPOSE(...) BOOST_PP_SEQ_FOLD_LEFT(OP, BOOST_PP_SEQ_HEAD(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)), BOOST_PP_SEQ_TAIL(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))) 

#define arg1 foo
#define arg2 bar
#define arg3 baz

COMPOSE(arg1, arg2, arg3)



回答2:


What about:

#include <iostream>

#define COMPOSE(prefix,name) prefix##_##name


int main() {
    int COMPOSE(first,par);

    first_par = 1;

    return first_par;
}


来源:https://stackoverflow.com/questions/31076419/c-preprocessor-join-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!