Nicolás Brailovsky


A modern blog

More preprocessor wizardy: strings

author Posted by: nico on date Aug 25th, 2009 | filed Filed under: C++, Programming
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 (*):

  1. class FooBar {
  2.    public:
  3.    const char* get_name(){ return "FooBar"; }
  4. };

Why would you type ALL that when you can make a simple macro, MK_CLASS, like this:

  1. MK_CLASS( FooBar )
  2.    /* Other methods */
  3. };

Problem is, this will only print “Name”:

  1. #define MK_CLASS( Name ) \
  2.       class Name { public: \
  3.             const char *get_name(){ return "Name"; }

Well, it’s an easy fix, just prepend # to your string, like this:

  1. #define MK_CLASS( Name ) \
  2.       class Name { public: \
  3.             const char *get_name(){ return #Name; }

Or use this nice string maker:

  1. #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

trackback Trackback URI | rsscomment Comments RSS