c++ - Macro string concatenation -
i use macros concatenate strings, such as:
#define str1 "first" #define str2 "second" #define strcat(a, b) b
which having strcat(str1 , str2 )
produces "firstsecond"
.
somewhere else have strings associated enums in way:
enum class myenum { value1, value2 } const char* myenumstring[] = { "value1string", "value2string" }
now following not work:
strcat(str1, myenumstring[(int)myenum::value1])
i wondering whether possible build macro concatenate #define
d string literal const char*
? otherwise, guess i'll without macro, e.g. in way (but maybe have better way):
std::string s = std::string(str1) + myenumstring[(int)myenum::value1];
the macro works on string literals, i.e. sequence of characters enclosed in double quotes. reason macro works c++ standard treats adjacent string literals single string literal. in other words, there no difference compiler if write
"quick" "brown" "fox"
or
"quickbrownfox"
the concatenation performed @ compile time, before program starts running.
concatenation of const char*
variables needs happen @ runtime, because character pointers (or other pointers, matter) not exist until runtime. why cannot concat
macro. can use std::string
concatenation, though - 1 of easiest solutions problem.
Comments
Post a Comment