user1810087
user1810087

Reputation: 5334

define macro with template as variable

i'm trying to use a macro to create some static variables.

my problem is, how do i do define a macro with 2 parameters, the first is a template and the second a static variable. the template should have more than 1 type.

for example:

#define macro(x, y, z, v) x::y z = v;

int main(int argc, char *argv[]) {
  // this works
  macro(std::queue<int>, value_type, test, 4)
  // this also works
  std::pair<int, int>::first_type x = 3;

  // this is produsing some compiler errors
  macro(std::pair<int, int>, first_type, test2, 4)

  return 0;
}

and is it even possible to do this?

here is the error:

main.cpp(47) : warning C4002: too many actual parameters for macro 'macro'
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::'
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::'
main.cpp(47) : error C2143: syntax error : missing ',' before '::'
main.cpp(50) : error C2143: syntax error : missing ';' before '}'
main.cpp(51) : error C2143: syntax error : missing ';' before '}'

inspired by Joachim Pileborg

#define macro(x, y, z, v, ...) x<__VA_ARGS__>::y z = v;
...

// now it works
macro(std::pair, first_type, test2, 4, int, int)

thx Joachim

Upvotes: 0

Views: 5425

Answers (3)

Daniel Frey
Daniel Frey

Reputation: 56863

It's not really a solution but merely a work-around:

#define COMMA ,

macro(std::pair<int COMMA int>, first_type, test2, 4)

or a little bit more readable:

#define wrap(...) __VA_ARGS__

macro(wrap(std::pair<int, int>), first_type, test2, 4)

Upvotes: 3

Pete Becker
Pete Becker

Reputation: 76245

There are a couple of ways to get rid of that top-level comma.

typedef std::pair<int, int> int_pair;
macro(int_pair, first_type, test2, 4)

macro((std::pair<int, int>), first_type, test2, 4);

#define macro2(x1, x2, y, z, v) x1, x2::y z = v;
macro2(std::pair<int, int> first_type, test2, 4)

Incidentally, I'd leave off the ; from the macro, and use it wherever the macro is used. That makes the code look more natural.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

It's because the preprocessor that handles macros is quite stupid. It sees five arguments in the second macro "call", the first one being std::pair<int and the second one int>. You can't have macro arguments that contains comma.

You might want to look into variadic macros, and re-arrange so that the class is last in the macro.

Upvotes: 2

Related Questions