简体   繁体   中英

C++ make a string raw using macros

So to make a string in C++ raw you do

std::string raw = R"raw_string(text_here""n/whatever)raw_string"

but my question is can you make a macro that preprocesses the string,
so its raw but it looks normal in code?? Like in a function argument

#define start_raw_string R"raw_string(
#define end_raw_string )raw_string"

void example(std::string raw_text){
    std::cout << start_raw_string raw_text end_raw_string << std::endl;
// here all this  ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾   is
// an entire string ...
// equivalent to R"raw_string(<RAW_TEXT_HERE>)raw_string"
}
int main(){
    example("text_here""n/whatever");
    // will print >> text_here""n/whatever
}

as you can see by highlighting it will not work like this for sure
so any workaround? found something about macro glue-ing here
https://www.iar.com/knowledge/learn/programming/advanced-preprocessor-tips-and-tricks/

but tried it and cant get it to work... soo? it should be posibile because its not
compile-time.

It cannot work like this. Once you passed the string literal to the function it is a std::string not a literal anymore. A string literal is the thing you type in your code. Its not something that you can pass around. Even if you'd pass a char[N] to the function it cannot work. You cannot turn a character array to a literal (hence also not to a raw literal).

Note that the syntax is like it is for a reason. The start/end character sequence appears right with the raw string literal, because the raw string literal cannot contain that sequence. Compare this:

std::cout << R"x()x")x";  // error

where it is obvious what the error is: The raw string literal cannot contain )x" , with this:

std::cout << macro_voodoo(")x") // error ?!?

which looks fine but would result in confusing error messages because the start and end character sequences are not visible in the code.

Write code for readability and clarity and don't try to work around C++ syntax. 5 characters to denote that a string literal is raw should be acceptable. And it can even be 3 only when you do not need the delimiter.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM