5

Let's have

class Item{
public:
    Item(int id,const char *name,const char *props=NULL);
};

And I want to write:

ITEM(1,FIRST);
ITEM(2,SECOND, WithSomeProps);

With a macro

#define ITEM(ID,NAME,...) new Item(ID,NAME, #__VA_ARGS__ )

That #__VA_ARGS__ compiles well on gcc but gives an error on VStudio. Is there a solid and portable solution?

I want to have a collection of ITEM() in a .h file that will be included several times with different #definitions of ITEM.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tru7
  • 6,348
  • 5
  • 35
  • 59
  • 1
    Why would you want to do this over just typing `new Item( ID, NAME, OTHER_ARGS )`? – Thomas Russell Jul 10 '14 at 20:52
  • 7
    Why do you need this? since third input argument of the constructor is defaulted you can call `Item(1, FIRST)` and `Item(2, SECOND, WithSomeProps)`. – 101010 Jul 10 '14 at 20:52
  • 2
    Why the wild `new` hidden behind a macro? – Shoe Jul 10 '14 at 20:56
  • 4
    Dubious motives not withstanding, I find it interesting whether stringization of the `__VA_ARGS__` pseudoargument is standard CPP. – Kerrek SB Jul 10 '14 at 21:01
  • @KerrekSB, It definitely is. At first sight check out § 16.3.5/9. – chris Jul 10 '14 at 21:02
  • 1
    The actual use is a bit more complex and I thought to make a simple example of what I wanted to achieve and clarify the possibility. – tru7 Jul 10 '14 at 22:24
  • ... always post the real code that reproduces the error. – Puppy Jul 13 '14 at 09:50

1 Answers1

0

GCC and Visual Studio handle Variadic Macros differently, because Macros are based on the compiler preprocessor (they are expanded at preprocessing time).

One of the difference is how they handle the empty variadic macros. One of them will allow empty __VA_ARGS__ while the other will cause a compiler error if the __VA_ARGS__ is empty.

On your example the first the line ITEM(1,FIRST) will cause an error at compile time, while working ok on the other .

One workaround for this is to have an empty first argument, so your constructor will be something like :

Item(int id,const char *name,void *allwaysNull, const char *props=NULL);

And then have your Macro initialziations like this

ITEM(1,0,FIRST)
ITEM(2,0,SECOND,WithSomeProps)

What is weird is that from my experience it was GCC that was having problems with empty VA_ARGS for variadic macros...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MichaelCMS
  • 4,703
  • 2
  • 23
  • 29
  • Is **VA_AGS** a mistype? – ikh Jul 11 '14 at 10:00
  • Hi @MIchaelCMS I haven't tried but it seems that your ida would overcome the problem with the missing emtpy argument but what I can not see is how this may help to stringize VA_ARGS – tru7 Jul 14 '14 at 17:33