Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unstringize inside a Macro

Tags:

c++

Inside a Macro, I can use the stringizing operator #:

#define STRINGIZE(name) #name

cout << STRINGIZE(SomeClass) << endl; // Prints "SomeClass"

Is it possible to do the opposite, unstringize inside a Macro? How?

For example:

#define RUN_FUNCTION(name) UNSTRINGIZE(name)();

void myFunction {
  cout << "Hello!" << endl;
}

RUN_FUNCTION("myFunction") // Prints "Hello!"

If not, is there a reason why?

like image 220
alestanis Avatar asked Nov 02 '12 21:11

alestanis


People also ask

Can macro have space?

Spaces are produced, inside a macro as elsewhere, by space or tab characters, or by end-of-line characters.

What is Stringizing operator in C?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

How do you define a string macro?

We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2.

What is the purpose of the operator in a macro definition?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.


2 Answers

No, it's not possible. The C++ preprocessor cannot break up tokens into smaller tokens in any way.

What exactly is it that you're trying to do? There's almost certainly a better way of doing it.

like image 120
Adam Rosenfield Avatar answered Oct 11 '22 08:10

Adam Rosenfield


[Promoted from comment]
Preprocessing takes place before compilation, which is before runtime. You'd need reflection to do that without defining your own rules, which requires some form of metadata, and C++ doesn't have it.

I can't find where, but I recently saw somewhere (perhaps here, but according to Wikipedia, it's been postponed) that reflection could be coming to C++ sometime in the future, so there might be a prospect there.

like image 28
chris Avatar answered Oct 11 '22 08:10

chris