More preprocessor wizardy: strings

No preprocesor wizard should go out of his house without the always useful string maker. Let’s say you’re trying to create a class with some sort of pseudo type-system (*):

class FooBar {
   public:
   const char* get_name(){ return "FooBar"; }
};

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.

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s