samedi 1 décembre 2018

C++ preprocessor : defer a macro call later

I am currently building my for_each macro. I did find some example on Stack overflow, so I take my inspiration from them, but I want to understand everything I do, so I come to ask questions ^^

I am trying to perform a "stop" recursion. So I write this code :

#include <iostream>

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

#define END(...)

#define MAP_END(...) 0, END
#define MAP_NEXT0(item, next, ...) next
#define MAP_NEXT(item, next) MAP_NEXT0(0, END, next) // This part for test

#define MAP_1(f, x, end) f(x) MAP_NEXT(end, MAP_0)(f, 0)

#define MAP(f, x, y) MAP_1(f, x, ())

int main() {
  MAP(PRINT_SQUARE, 5, 8);

  return 0;
}

This code works. However I have this line #define MAP_NEXT(item, next) MAP_NEXT0(0, END, next)

So, instead of doing it, I tried to replace the 0, END by a call to the macro MAP_END, but without success...

#include <iostream>

using namespace std;

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

#define FORCE_EXPANDING(x) x

#define END(...)

#define MAP_END(...) 0, END
#define MAP_NEXT0(item, next, ...) next
#define MAP_NEXT(item, next) MAP_NEXT0(MAP_END(), next)

#define MAP_1(f, x, end) f(x) MAP_NEXT(end, MAP_0)(f, 0)

#define MAP(f, x, y) MAP_1(f, x, ())

int main() {
  MAP(PRINT_SQUARE, 5, 8);

  return 0;
}

It does not compile :

..\main.cpp(20): error C2065: 'PRINT_SQUARE': undeclared identifier
..\main.cpp(20): error C3861: 'MAP_0': identifier not found

Aucun commentaire:

Enregistrer un commentaire