「More C++ Idioms/複文マクロ(Multi-statement Macro)」の版間の差分

削除された内容 追加された内容
Yak! (トーク | 投稿記録)
現内容を翻訳
1 行
=<center>複文マクロ(Multi-statement Macro)</center>=
=== Intent意図 ===
複文(複数行)のマクロを書く。
To write a multi-statement (multi-line) macro.
 
=== Also Known As別名 ===
 
=== Motivation同期 ===
2つ以上の分をまとめて1つのマクロにして、関数呼び出しのように呼び出すことが便利な場合がある。
Sometimes it is useful to group two or more statements into a macro and call them like a function call. Usually, an inline function should be the first preference but things such as debug macros are almost invariably macros rather than function calls. Grouping multiple statments into one macro in a naive way could lead to compilation errors, which are not obvious at first look. For example,
大抵 inline 関数が第一候補となるはずだが、デバッグ用途のようなものだとほとんど常に関数呼び出しよりもマクロになってしまう。
素朴な方法で、複数の文を 1 つのマクロにまとめた場合、ぱっと見では明らかではないコンパイルエラーを引き起こす場合がある。例えば、
 
<source lang="cpp">
12 ⟶ 14行目:
</source>
 
のようなマクロは、セミコロンが終端に付けられている場合、if 文のところでコンパイルエラーになる。
would fail in an if statement if a semi-colon is appended at the end.
 
<source lang="cpp">
if (cond)
MACRO(10,20); // Compiler error here because of the semi-colon.セミコロンによりここでコンパイルエラー
else
statement3;
</source>
 
上記の文は次のように展開され
The above statement expands to
 
<source lang="cpp">
if (cond)
{ statement1; statement2; }; // Compiler error here because of the semi-colon.セミコロンによりここでコンパイルエラー
else
statement3;
</source>
 
エラーが発生する。そのため、人々は、複文マクロに対して広く使われる、do-while ループを基本とするイディオムを考え出した。
giving a compiler error. Therefore, people came up with a widely used idiom for multi-statement macros, which is based on a do-while loop.
 
=== Solution and Sample Code解法とサンプルコード ===
以下に複文マクロ(Multi-statement Macro)イディオムの例を示す。
Here is an example of the multi-statement macro idiom.
<source lang="cpp">
#define MACRO(arg1, arg2) do { \
/* declarations, if any必要ならば宣言を入れることもできる */ \
statement1; \
statement2; \
/* ... */ \
} while(0) /* (no trailing終端の ; がない) */
</source>
 
呼び出し元でセミコロンを付け加えれば、この式は文脈に関わらず単一の文になる。
When the caller appends a semicolon, this expansion becomes a single statement regardless of the context. Optimizing compilers usually remove any dead tests, such as while(0). This idiom is not useful when macro is used as a parameter to a function call. Moreover, this idiom allows return statement.
最適化コンパイラは大抵 while(0) のような無意味なテストを取り除く。
このイディオムはマクロが関数呼び出しのパラメータとして呼び出される時には役に立たない。
なお、このイディオムではマクロ中で return 文を用いることができる。
 
<source lang="cpp">
func(MACRO(10,20)); // Syntax error here.ここで構文エラー。
</source>
 
=== Known Uses既知の利用 ===
ACE_NEW_RETURN, ACE_NEW_NORETURN macros in Adaptive Communication Environement (ACE). での ACE_NEW_RETURN、ACE_NEW_NORETURN マクロ。
<source lang="cpp">
#define ACE_NEW_RETURN(POINTER,CONSTRUCTOR,RET_VAL) \
58 ⟶ 63行目:
</source>
 
=== Related Idioms関連するイディオム ===
 
=== References ===
* [http://c-faq.com/cpp/multistmt.html What's the best way to write a multi-statement macro?]
 
[[en:More C++ Idioms/Multi-statement Macro]]
[[Category:{{BASEPAGENAME}}|ふくふんまくろ]]