1

I have a function that takes a pointer to a function as a parameter. This function get's called within a for loop due to the similar nature of the names of the function pointer I use a macro to expand the name into the function. IT looks something like this:

void fill(int, int(*funcbase)(int));
int funcbase0(int);
int funcbase1(int);
int funcbase2(int);
int funcbase3(int);
/// all the way through funcbase31

#define FILL_(num) fill(num, funcbase##num)
#define FILL(num) FILL_(num)

for(int i = 0; i < 32; i++)
    FILL(i);

I would like this to call fill for 0,1,2,... and funcbase0, funcbase1, funcbase2,... , but it calls fill with the second parameter of "funcbasei" It does not expand i every time.

Is what I'm trying to do possible? What compiler would I need to try? (I'm using gcc 4.9.3)

Luke Smith
  • 781
  • 3
  • 7
  • 15

2 Answers2

2

What you are trying to do is not possible with a macro because macros are expanded at compile time, well before the runtime and loops start running.

However, you can easily do this with a for loop on an array of function pointers:

typedef int(*funcbase_t)(int);
funcbase_t fbases[] = {
    funcbase0, funcbase1, funcbase2, funcbase3, ...
};

Now you can run your loop on fbase array:

for(int i = 0; i < 32; i++)
    fbases[i](i);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you I figured as much, Interesting approach! I should have mentioned that there are 256 of the funcbase's and I doubt I'll type it by hand. I'll probably write a bash or python script and cat it into my code. – Luke Smith Nov 24 '15 at 04:49
1

You can use the preprocessor to do this, by recursively splitting the interval into parts and calling it for each one. Or use the pre-built version in boost:

#include <boost/preprocessor/repetition/repeat.hpp>

// and in code
#define FILL_(num) fill(num, funcbase##num)
#define FILL(num) FILL_(num)
#define MACRO(z, n, text) FILL_(n);

BOOST_PP_REPEAT(4, MACRO, 0);
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • This is a great idea! unfortunately for my situation boost is not an option. I still believe someone else may find this useful! Thank you! – Luke Smith Nov 24 '15 at 19:45