p_tan's blog

勉強日記です。ツッコミ大歓迎

constexpr関数とstatic_assertでコンパイル時ユニットテスト

constexprな関数はstatic_assertでコンパイル時にユニットテストできる。

// ユークリッド互除法による最大公約数
constexpr int gcd(int a, int b)
{
    return b == 0 ? a : gcd(b, a % b);
} 

// constexprな関数gcdのユニットテスト
static_assert(gcd(1, 1) == 1, "gcd() test");
static_assert(gcd(4, 2) == 2, "gcd() test");
static_assert(gcd(4, 6) == 2, "gcd() test");
static_assert(gcd(3, 5) == 1, "gcd() test");

static_assertはブロック内でなくても書けるのが便利。しかも、コンパイル時にしかテストが走らないので、constexpr関数の直下にテストコードを書いておけば、ビルドで変更のあったファイルのみコンパイルすることで無駄なテストが走ることも少なくなる。すばらしい。