2

I want to develop by myself a kind of for_each macro. I built it from scratch because I found other implementation in this website too much complicate and I do not find any resources on internet to learn tricks and tips about macros.

So, what I began to do is to make a make a macro that prints the square of a value. after I created a macro MAP that call MAP_ONE that calls f with the first arg.

On clang and gcc, this code works well :

#include <iostream>

using namespace std;

#define PRINT_SQUARE(x) std::cout << x * x << std::endl;

#define MAP(f, ...) MAP_ONE(f, __VA_ARGS__)

#define MAP_ONE(f, x, ...) f(x)

int main() {
  MAP(PRINT_SQUARE, 5, 8);
  return 0;
}

On MSVC it does not work. The errors are :

..\main.cpp(12): error C2563: mismatch in formal parameter list
..\main.cpp(12): error C2568: '<<': unable to resolve function overload
..\main.cpp(12): note: could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'

Is it a MSVC bug or is it normal and I just did something forbiden?

Thanks to the answer of Afshin, I modified the prior code to :

#include <iostream>

using namespace std;

#define PRINT_SQUARE(x) std::cout << ((x) * (x)) << std::endl;

#define MAP(f, ...) MAP_ONE(f, __VA_ARGS__)

#define MAP_ONE(f, x, ...) f(x) f(__VA_ARGS__)

int main() {
  MAP(PRINT_SQUARE, 5, 8);
  return 0;
}

On clang and GCC it prints : 25 and 64. On MSVC it does not compile :

D:\Desktop\Programmation\macro\main.cpp:12: error: C2059: syntax error: ')'
Antoine Morrier
  • 3,930
  • 16
  • 37

1 Answers1

1

UPDATE:

This solves the problem:

#include <iostream>

using namespace std;

#define EXPAND(x) x

#define PRINT_SQUARE(x) std::cout << x * x << std::endl;

#define MAP_ONE(f, x, ...) f(x)

#define MAP(f, ...) EXPAND(MAP_ONE(f, __VA_ARGS__ ))

int main() {
  MAP(PRINT_SQUARE, 5, 8);
  return 0;
}

Thanks to this link. It seems there is problem with expanding __VA_ARGS__ in VS and this trick will solve the problem.

Afshin
  • 8,839
  • 1
  • 18
  • 53