How can macro take a number in this way (or can it) :
#define MYMACRO(x) (x)
int val = 5;
MYMACRO(val);
seems it produces val.
I need to have a macro that takes a string and a size_t and produces a
function name.
If I call it :
MYMACRO(function, val)();
it should call function5();
Is it possible?
You can do this (sort of), but something tells me it isn't what you
need:
// test_macro.cpp
#define MYMACRO(function,val) function##val##(##)
#include <iostream>
#include <ostream>
void func1() { std::cout << "Called func1" << std::endl; }
void func2() { std::cout << "Called func2" << std::endl; }
void func3() { std::cout << "Called func3" << std::endl; }
void func4() { std::cout << "Called func4" << std::endl; }
void func5() { std::cout << "Called func5" << std::endl; }
int main()
{
MYMACRO(func,1);
MYMACRO(func,2);
MYMACRO(func,3);
MYMACRO(func,4);
MYMACRO(func,5);
}
Actually, you could do this much better with a template function, and
it would have the tremendous advantage over a macro of being typesafe!
The problem is probably that you need to choose a function dynamically
according to some runtime value. This macro can't do that because it
performs text substitution before the compiler ever gets around to
compiling your code.
To do this, you need function pointers and some kind of mapping from
strings (or integers, or whatever you use for a key) to function
pointers. std::map<> would serve you well, I believe.