简体   繁体   中英

Parsing dynamic-array elements as arguments? (variadic)

trying to find a (probably) preprocessing trick which will do something similar to the next pseudo C++

myVariadicFun(argv[0],argv[1],argv[2],...,argv[argc] );

the variadic function is ready and working, just need to parse the array arguments in it.

reason for not just passing an array pointer is because im playing with constexpr / metaprogramming actually.

With [Boost.Preprocessor] you can easily achieve appropriate code generation for your needs described in the screenshot:

#include <boost/preprocessor/repetition/enum.hpp>

#define ARRAY_ELEMENTS(z, n, arrVar) arrVar[n]

#define EXPAND_ARRAY(N, arrVar) \
  BOOST_PP_ENUM(N, ARRAY_ELEMENTS, arrVar)

#define EXPAND_CASE(N, arrVar) \
    case N: cout << crawler(EXPAND_ARRAY(N, arrVar)).best_sum << endl; break

int main(int argc, char* argv[]) {
    char** input = &argv[1];
    --args;
    switch(argc) {
    EXPAND_CASE(1, input);
    EXPAND_CASE(2, input);
    EXPAND_CASE(3, input);
    }
}

BOOST_PP_REPEAT_FROM_TO allows to perform further code folding:

#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>

#define ARRAY_ELEMENTS(z, n, arrVar) arrVar[n]

#define EXPAND_ARRAY(N, arrVar) \
  BOOST_PP_ENUM(N, ARRAY_ELEMENTS, arrVar)

#define EXPAND_CASE_Z(z, N, arrVar) \
 case N: cout << crawler(EXPAND_ARRAY(N, arrVar)).best_sum << endl; break;

// actually each OS has its own limitation for maximal number of arguments, see your
// OS docs for more info. Beware Boost.Preprocessor has its own limits for repeatable
// macros expansions
#define MAX_ARGS 100

int main(int argc, char* argv[]) {
    char** input = &argv[1];
    --args;
    switch(argc) {
    BOOST_PP_REPEAT_FROM_TO(1, MAX_ARGS, EXPAND_CASE_Z, input);
    }
}

But frankly speaking I doubt variadic template functions are intended to be used this way.

不,根据定义,您不能将动态大小的数组(即其大小在执行时定义)与编译时间大小推导一起使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM