替代運算子表示
C++(和 C)原始碼可以用任何非 ASCII 的 7 位字元集編寫,只要它包含 ISO 646:1983 不變字元集。然而,一些 C++ 運算子和標點符號需要 ISO 646 字元集之外的字元:{, }, [, ], #, \, ^, |, ~
。為了能夠使用某些或所有這些符號不存在的字元編碼(例如德國的 DIN 66003),C++ 定義了以下由 ISO 646 相容字元組成的替代表示。
目錄 |
[編輯] 替代記號
對於某些使用非 ISO646 字元的運算子和其他記號,存在替代拼寫。在語言的所有方面,每個替代記號的行為都與它的主要記號完全相同,除了它的拼寫(字串化運算子可以使拼寫可見)。這兩個字母的替代記號有時被稱為“二合字母”。儘管是四個字母長,%:%: 也被認為是一個二合字母。
主要 | 備選項 |
---|---|
&&
|
和 |
&=
|
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 文件 關於 替代運算子和記號
|