在C++中用“$”编写原始字符串的正确格式是什么?

我正在从关于常量的cplusplus.com 教程中学习 C++ 中的原始字符串。根据该站点上的定义,原始字符串应R"sequence()sequencewhere开始和结束,wheresequence可以是任何字符序列。

该网站的示例之一如下:

R"&%$(string with backslash)&%$"

但是,当我尝试编译包含上述原始字符串的代码时,出现编译错误。

test.cpp:5:28: error: invalid character '$' in raw string delimiter
    5 |     std::string str = R"&%$(string with backslash)&%$";
      |                       ^
test.cpp:5:23: error: stray 'R' in program

我在 Windows 和 Linux 上使用 g++ 和 clang++ 进行了尝试。他们都没有工作。

回答

从C++ 参考:

delimiter:由除括号、反斜杠和空格以外的任何源字符组成的字符序列(可以为空,最多 16 个字符长)

请注意此处的“任何源字符”部分。

让我们看看标准是怎么说的:

来自[gram.lex]

原始字符串
  “ d-char-sequence optr-char-sequenceoptd-char-sequence opt

...

d-char-sequence :
  d-char
  d-char-sequence d-char

d-char
  基本源字符集的任何成员,除了:空格、左括号(、右括号)、反斜杠和代表水平制表符、垂直制表符、换页和换行符的控制字符。

那么,基本的源字符集是什么?来自[lex.charset]

基本源字符集由 96 个字符组成:空格字符、代表水平制表符、垂直制表符、换页符和换行符的控制字符,以及以下 91 个图形字符:

abcdefghijklmnopqrstu vwxyz ABCDEFGHIJKLMNOPQRSTU VWXYZ 0 1 2 3 4 5 6 7 8 9_ { } [] # ( ) < > % : ; . ? * + - / ^ & |~! = , " '

...其中不包括$; 所以结论是美元符号$不能成为分隔符序列的一部分。

  • So in short: use cppreference.com, not cplusplus.com. The latter tends to have many more inaccuracies like that, and the wasted time piles up.
  • @AntoninGAVREL: What is there to fix? Just don't try to use it here. There's no particular reason to.
  • @drescherjm It doesn't exclude `$` from the body of the literal, just the delimiter. Almost always, you can find a pretty good delimiter out of (more than) the `88 ^ 16` combinations.

以上是在C++中用“$”编写原始字符串的正确格式是什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>