The Mask
The Mask

Reputation: 17447

Can a macro accept a list-initialization as argument?

Any work around to make the below code work? it currently give the following error:

error: too many arguments provided to function-like macro invocation
         X({1,2,3});
                             ^

code:

#include <stdio.h>
#define X(a) a,

int main()
{
    mystruct = X({1,2,3}));
}

I tried something with templates but so far I know (I'm a bit new to C++) templates aren't "powerful" enough to implement something like the X macro. As you may already noticied, what I'm looking for is implement something like the X macro. Others ideas to do this are very welcome too as long as everything is know at compile-time.

Upvotes: 0

Views: 1236

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

This does the trick:

#define X(...) __VA_ARGS__

struct mystruct {
    int a,b,c;
};

int main() {
    mystruct s = X({1,2,3});
}

Or as a variation:

#define X(...) {__VA_ARGS__}

struct mystruct {
   int a,b,c;
};

int main() {
   mystruct s = X(1,2,3);
}

Upvotes: 1

Related Questions