简体   繁体   中英

Initialize array of struct with vectors

I have struct:

enum VAR;
typedef void (*VoidF)();
struct Function
{
    const char* name;
    VAR return_type;
    vector<VAR> args;
    VoidF f;
};

And I can initialize it like this in VS2013:

const Function funcs[] = {
    "print", V_VOID, { V_STRING }, f_print,
    "pause", V_VOID, {}, f_pause,
    "getstr", V_STRING, {}, f_getstr,
    "getint", V_INT, {}, f_getint,
    "pow", V_INT, { V_FLOAT, V_FLOAT }, f_pow,
    "getfloat", V_FLOAT, {}, f_getfloat
};

But I need this to work in VS2008 too. Is there any other way then changing this to function and pushing vector elements one by one? I have this code on git and it need to work with both versions.

VS2008 don't support features from C++11.

Found some related answers here: What is the easiest way to initialize a std::vector with hardcoded elements?

Decided to write it like this:

Function::Function(cstring name, VAR return_type, VoidF f, ...) : name(name), return_type(return_type), f(f)
{
    va_list a;
    va_start(a, f);
    while(true)
    {
        VAR type = va_arg(a, VAR);
        if(type == V_VOID)
            break;
        else
            args.push_back(type);
    }
    va_end(a);
}

const Function funcs[] = {
    Function("print", V_VOID, f_print, V_STRING, V_VOID),
    Function("pause", V_VOID, f_pause, V_VOID),
    Function("getstr", V_STRING, f_getstr, V_VOID),
    Function("getint", V_INT, f_getint, V_VOID),
    Function("pow", V_FLOAT, f_pow, V_FLOAT, V_FLOAT, V_VOID),
    Function("getfloat", V_FLOAT, f_getfloat, V_VOID)
};

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