I have a macro like this.
#define TO_STR(x) #x
I can use this macro to make string without the input string between char "
. Like :
const char* test = TO_STR(hello,macro);
std::cout << test << std::endl;
I can got : hello,macro
correctly .
My question is : how can I deal with char #
in the input string . Like :
const char* shaderprogram = TO_STR(#version 300 es \n);
This will cause an error , any suggestion ?
The first is illformed, since the preprocessor will treat the ,
as separating two arguments, not as part of an argument.
You could try creating a second macro
#define TO_STR2(a,b) TO_STR(a) "," TO_STR(b)
If you then want to do the same with three arguments, you would need to define another macro
#define TO_STR3(a,b,c) TO_STR2(a,b) "," TO_STR(c)
which is possible for more arguments, but messy - after all, macros aren't really intended to be used for this sort of thing.
The solution to the second is easy
const char* shaderprogram = "#" TO_STR(version 300 es \n);
The real solution, however, is to get away from any obsession of having a macro that allows you to leave the "
characters off string literals. Only use the stringizing operator in a macro when it is the ONLY solution to the problem, not as the first tool of choice when there are alternatives.
After all, this
const char* shaderprogram = "#" TO_STR(version 300 es \n); // blech!
is inferior to
const char* shaderprogram = "#version 300 es \n";
by several measures - including readability, maintainability, etc etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.