Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c++ - Iterating Variadic Macro Arguments

I am programmatically generating bunch of functors, in order to keep the generated code more readable I am trying to come up with a macro that will expand line the following,

SET_STATE(FunctorA,a,b);

ref a;
ref b;
FunctorA(ref a, ref b){
   this->a = a;
   this->b = b;
}

Basically it will expand to the first arguments constructor. Variadic part is the number of arguments to the constructor. is it possible to loop inside the macro and generate this code during preprocessing even though it does not make sense for this particular case but I have some functors that have 20 or so variables that they have access to it will cleanup my generated code a lot.

All arguments will be of the same type, only names will differ.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If boost::preprocessor and SEQ representation((a)(b)...) are allowed, probably the following code will meet the purpose:

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>

#define DEF_MEMBER( r, data, elem ) ref elem;
#define DEF_PARAM( r, data, i, elem ) BOOST_PP_COMMA_IF( i ) ref elem
#define DEF_ASSIGN( r, data, elem ) this->elem = elem;

#define SET_STATE( f, members )                         
  BOOST_PP_SEQ_FOR_EACH( DEF_MEMBER,, members )         
  f( BOOST_PP_SEQ_FOR_EACH_I( DEF_PARAM,, members ) ) { 
      BOOST_PP_SEQ_FOR_EACH( DEF_ASSIGN,, members )     
  }

SET_STATE(FunctorA,(a)(b))

The above code is expanded to

ref a; ref b; FunctorA( ref a , ref b ) { this->a = a; this->b = b; }

in my environment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...