Thomas Eding
Thomas Eding

Reputation: 1

Get all function parameter names

An example of what I want is this:

char const * bar (T1 x, T2 y) {
    return "bar";
}

char const * foo (T1 z, T2 w) {
    return bar(__PARAMS__);
}

should expand to

char const * bar (T1 x, T2 y) {
    return "bar";
}

char const * foo (T1 z, T2 w) {
    return bar(z, w);
}

Is there any way to achieve anything remotely like this without hand-writing it?

Reason: This would help with template metaprogramming for a code generation scheme I want to implement. It would allow me to literally copy and paste the lines. Something around the (ahem!) lines of

void f0 () {
    DumpCode(__PARAMS__); // DumpCode();
}

void f1 (T1 x) {
    DumpCode(__PARAMS__); // DumpCode(x);
}

void f2 (T1 x, T2 y) {
    DumpCode(__PARAMS__); // DumpCode(x, y);
}

Upvotes: 2

Views: 3120

Answers (1)

Quuxplusone
Quuxplusone

Reputation: 26949

There's no way in C or even C++ to programmatically get the names or types of the current function's arguments, nor the current function itself. The closest thing they let you get is __func__, which is merely a string representation of the name of the current function.

So you're going to have to capture the parameters' names somewhere so that you can use them in the parameter-list and also in the argument-list to DumpCode. When we want to capture a chunk of text and then substitute it into two places at once, that calls for a macro.

As for selectively expanding the types, that's fairly easy as long as all your types are typedef'ed. If you have to deal with selectively expanding int (*x)() versus x, you'll have to refactor this code to be quite a bit uglier.

#define PARAMS(x) x
#define ARGS(x)

#define P(TYPE) TYPE(T1) z, TYPE(T2) w
char const * foo (P(PARAMS)) {
    return bar(P(ARGS));
}
#undef P

#define P(TYPE)
void f0 (P(PARAMS)) {
    DumpCode(P(ARGS)); // DumpCode();
}
#undef P

#define P(TYPE) TYPE(T1) x
void f1 (P(PARAMS)) {
    DumpCode(P(ARGS)); // DumpCode(x);
}
#undef P

#define P(TYPE) TYPE(T1) x, TYPE(T2) y
void f2 (P(PARAMS)) {
    DumpCode(P(ARGS)); // DumpCode(x, y);
}
#undef P

Upvotes: 3

Related Questions