Linux Kernel の黒魔術マクロ: __is_constexpr(x)
__is_constexpr(x)
は Linux kernel 4.17 で導入されたマクロで、与えられた式が定数式であるかを 式を評価せずに 判定する。
/* * This returns a constant expression while determining if an argument is * a constant expression, most importantly without evaluating the argument. * Glory to Martin Uecker <Martin.Uecker@med.uni-goettingen.de> */ #define __is_constexpr(x) \ (sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8)))
kernel/git/torvalds/linux.git - Linux kernel source tree
Linus さんも「それはアイデアとは言わねえ。天才かマジで病んだ頭脳のどっちかだわ」(適当訳) とべた褒めしている。
LKML: Linus Torvalds: Re: detecting integer constant expressions in macros
サンプルコード:
#include <stdio.h> #define __is_constexpr(x) \ (sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8))) #define sq(x) ((x) * (x)) int main(void) { int a = 2; if (__is_constexpr(sq(2))) puts("Yes"); else puts("No"); if (__is_constexpr(sq(a))) puts("Yes"); else puts("No"); return 0; }
実行結果:
Yes No
はい天才。
解説は暇があったら書くが、既にある: