开发者

C/C++ preprocessor single quote? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How to single-quote an argument in a macro?

开发者_开发技巧

How can it do the following:

#define MACRO(X) ...
MACRO(a) // should give 'a'


I might be missing an easier way, but how about #define MACRO(X) ((#X)[0]). The # stringtizes X and then [0] selects the first character.


Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:

There is no way to convert a macro argument into a character constant.


Like this:

#include <string>

std::string Macro(const std::string& s)
{
  std::string ret = "'";
  ret += s;
  ret += "'";
  return ret;
}

EDIT:

I posted this answer before it was revealed that this was needed for metaprogramming. I don not know of a way to accomplish this for metaprogramming, but metaprogramming is not my forte.

Also, as for why I am effectively saying "don't use the preprocessor" in the first place, read the comments below. But in short, I believe that almost everything that is commonly done using the preprocessor can and should be done using first-level constructs instead. Using the preprocessor skirts the C++ type system and reduces safety. Macros are difficult to debug, difficult to extend. Extensively using macros will result in code that isn't familiar to the programmers who didn't create the macro, resulting in a kind of "secret language" only 1 person knows, decreasing maintainability of not only the macros, but the functions where they are used.

OK, I guess that wasn't so short, but there it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜