1

C++ preprocessor __VA_ARGS__ number of arguments

The accepted answer there doesn't work for me. I've tried with MSVC++ 10 and g++ 3.4.5.

I also crunched the example down into something smaller and started trying to get some information printed out to me in the error:

template < typename T >
struct print;

#include <boost/mpl/vector_c.hpp>

#define RSEQ_N 10,9,8,7,6,5,4,3,2,1,0
#define ARG_N(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N
#define ARG_N_(...) ARG_N(__VA_ARGS__)

#define XXX 5,RSEQ_N

#include <iostream>
int main()
{
  print< boost::mpl::vector_c<int, ARG_N_( XXX ) > > g; // ARG_N doesn't work either.
}

It appears to me that the argument for ARG_N ends up being 'XXX' instead of 5,RSEQ_N and much less 5,10,...,0. The error output of g++ more specifically says that only one argument is supplied.

Having trouble believing that the answer would be proposed and then accepted when it totally fails to work, so what am I doing wrong? Why is XXX being interpreted as the argument and not being expanded? In my own messing around everything works fine until I try to pass off VA_ARGS to a macro containing some names followed by ... like so:

#define WTF(X,Y,...) X , Y , __VA_ARGS__
#define WOT(...) WTF(__VA_ARGS__)

WOT(52,2,5,2,2)

I've tried both with and without () in the various macros that take no input.

Community
  • 1
  • 1
Edward Strange
  • 40,307
  • 7
  • 73
  • 125
  • After taking all the c++ stuff out I tried with gcc. It hates it too. – Edward Strange Jan 07 '11 at 22:59
  • Roberts: I can't help but think that there's a better way to do what you want. To what end are you trying to achieve with something like this? – In silico Jan 07 '11 at 23:39
  • @In silico - I'm trying to find the number of elements in a boost PP tuple. – Edward Strange Jan 08 '11 at 00:15
  • [This answer in C++ preprocessor __VA_ARGS__ number of arguments](http://stackoverflow.com/questions/2124339/c-preprocessor-va-args-number-of-arguments/5756072#5756072) worked for me. – Jon Nov 28 '11 at 07:25

2 Answers2

1

__VA_ARGS__ was originally introduced in C99 and prior to C++11 was not part of the C++ standard. The compiler you’re referencing here doesn’t support C++11 (I believe), though more modern compilers should be able to handle this just fine.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Most C++ compilers support `__VA_ARGS__` as an extension. Variadic macros will be part of the C++0x standard. – In silico Jan 07 '11 at 23:29
1

I don't see anything wrong with your macros.

Using both g++ 4.5.1 (in C++0x mode) and mcpp, ARG_N_( XXX ) is correctly replaced by 1.

This is a reported bug in Visual C++.

James McNellis
  • 348,265
  • 75
  • 913
  • 977