More preprocessor wizardy: strings
Posted by: nico on
Aug 25th, 2009 |
Filed under: C++, Programming
Why would you type ALL that when you can make a simple macro, MK_CLASS, like this:
-
MK_CLASS( FooBar )
-
/* Other methods */
-
};
Problem is, this will only print “Name”:
-
#define MK_CLASS( Name ) \
-
class Name { public: \
-
const char *get_name(){ return "Name"; }
Well, it’s an easy fix, just prepend # to your string, like this:
-
#define MK_CLASS( Name ) \
-
class Name { public: \
-
const char *get_name(){ return #Name; }
Or use this nice string maker:
-
#define MK_STR(str) #str
As usual, use the preprocesor at your own risk.
(*) Yeah, I know, OO purists will try to beat me to death for this, but it actually has some uses. I’ve found it to be a specially good solution when working with low level protocols.



Add A Comment