Macro taking input from surrounding context
I know this is probably a bit of a stretch to ask, but I was wondering if there was any way to do this nicely:
I have a function map:
std::map<std::string, std::function<int(int)> > fnmap;
And a bunch of functions that I'd lik开发者_Python百科e to add to this map.
Is there any way to decorate the functions so that I can just have:
MAPNAME("FN") int fn(int param) {}
MAPNAME("FN2") int fn2(int param2) {}
..
which should result in fnmap["FN"] = &fn;
As I said above, this is a bit of a stretch, but, I figured worth asking!
struct Remember {
static std::map<std::string, std::function<int(int)> > map;
Remember (int (*f) (int), const char * name) {
map [name] = f;
}
};
// Needs anonymous namespace to be able to include it more than once in a header.
#define MAPNAME(x) namespace {Remember _##__LINE__ (x, #x);}
int f1 (int);
int f2 (int);
MAPNAME (f1)
MAPNAME (f2)
The functions need to be declared before you invoke MAPNAME
, so it doesn't really count as decoration.
Macros don't understand C styntax, so they can't pull in any "context" which you haven't given them.
精彩评论