命名空间
变体
操作

操作符的替代表示

来自 cppreference.cn
< cpp‎ | 语言
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
范围for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (在 C++17* 中弃用)
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储期说明符
初始化
 
 

C++(和 C)源代码可以使用任何包含 ISO 646:1983 不变字符集的非 ASCII 7 位字符集编写。但是,几个 C++ 运算符和标点符号需要 ISO 646 代码集之外的字符:{, }, [, ], #, \, ^, |, ~。为了能够使用其中一些或所有这些符号不存在的字符编码(例如德语 DIN 66003),C++ 定义了以下由 ISO 646 兼容字符组成的替代方案。

目录

[编辑] 替代记号

对于几个运算符和其他使用非 ISO646 字符的记号,存在替代拼写。在语言的所有方面,除了拼写之外,每个替代记号的行为都与其主要记号完全相同(字符串化运算符 可以使拼写可见)。双字母替代记号有时称为“二合字母”。尽管有四个字母长,%:%: 也被认为是二合字母。

主要 替代
&& and
&= and_eq
& bitand
| bitor
~ compl
! not
!= not_eq
|| or
|= or_eq
^ xor
^= xor_eq
{ <%
} %>
[ <:
] :>
# %:
## %:%:

[编辑] 三字符组 (C++17 中移除)

以下三字符组(三字符组)在 解析注释和字符串字面量之前被解析,并且每次出现三字符组都会被替换为相应的基本字符

主要 三字符组
{ ??<
} ??>
[ ??(
] ??)
# ??=
\ ??/
^ ??'
| ??!
~ ??-

由于三字符组处理得很早,因此像 // Will the next line be executed?????/ 这样的注释将有效地注释掉下一行,而像 "Enter date ??/??/??" 这样的字符串字面量被解析为 "Enter date \\??"

[编辑] 注意

字符 &! 在 ISO-646 下是不变的,但是无论如何,都为使用这些字符的记号提供了替代方案,以适应更严格的历史字符集。

对于相等运算符 == 没有替代拼写(例如 eq),因为字符 = 存在于所有受支持的字符集中。

[编辑] 与 C 的兼容性

相同的单词在 C 编程语言的头文件 <iso646.h> 中定义为宏。因为在 C++ 中,这些是内置于语言中的,所以 C++ 版本的 <iso646.h> 以及 <ciso646> 没有定义任何内容。但是,非单词二合字母(例如 <%)是核心语言的一部分,可以在不包含任何头文件的情况下使用(否则,在任何缺少 # 的字符集上都将无法使用它们)。

[编辑] 关键字

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

[编辑] 示例

以下示例演示了几个替代记号的用法。

%:include <iostream>
 
struct X
<%
    compl X() <%%> // destructor
    X() <%%>
    X(const X bitand) = delete; // copy constructor
    // X(X and) = delete; // move constructor
 
    bool operator not_eq(const X bitand other)
    <%
       return this not_eq bitand other;
    %>
%>;
 
int main(int argc, char* argv<::>) 
<%
    // lambda with reference-capture:
    auto greet = <:bitand:>(const char* name)
    <%
        std::cout << "Hello " << name
                  << " from " << argv<:0:> << '\n';
    %>;
 
    if (argc > 1 and argv<:1:> not_eq nullptr)
        greet(argv<:1:>);
    else
        greet("Anon");
%>

可能输出

Hello Anon from ./a.out

[编辑] 参考文献

  • C++23 标准 (ISO/IEC 14882:2024)
  • 5.5 替代记号 [lex.digraph]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 5.5 替代记号 [lex.digraph]
  • C++17 标准 (ISO/IEC 14882:2017)
  • 5.5 替代记号 [lex.digraph]
  • C++14 标准 (ISO/IEC 14882:2014)
  • 2.4 三字符序列 [lex.trigraph]
  • 2.6 替代记号 [lex.digraph]
  • C++11 标准 (ISO/IEC 14882:2011)
  • 2.4 三字符序列 [lex.trigraph]
  • 2.6 替代记号 [lex.digraph]
  • C++03 标准 (ISO/IEC 14882:2003)
  • 2.3 三字符序列 [lex.trigraph]
  • 2.5 替代记号 [lex.digraph]
  • C++98 标准 (ISO/IEC 14882:1998)
  • 2.3 三字符序列 [lex.trigraph]
  • 2.5 替代记号 [lex.digraph]

[编辑] 另请参阅

C 文档 关于 替代操作符和记号