constexpr の再帰上限数
512 回以上であることが推奨されています.GCC 4.6.1 ではデフォルトで 512 回です.
repeated.cpp
// apply f n times to x template <class F, class T> constexpr T repeated(F f, unsigned n, T x) { return n == 0 ? x : repeated(f, n - 1, f(x)); } constexpr int inc(int x) { return x + 1; } static_assert(repeated(inc, 1000, 0) == 1000, "");
$ g++ -c -std=c++0x repeated.cpp repeated.cpp:5:48: in constexpr expansion of 'repeated [with F = int (*)(int), T = int](f, (n + -1u), f(x))' ... repeated.cpp:5:48: in constexpr expansion of 'f(x)' repeated.cpp:9:1 error: constexpr evaluation depth exceeds maximum of 512 (use -fconstexpr-depth= to increase the maximum)
上限を増やすには,-fconstexpr-depth= オプションを使います.
$ g++ -c -std=c++0x repeated.cpp -fconstexpr-depth=1001
あまり再帰が深すぎると,コンパイラがクラッシュしてしまうことがあります.再帰が浅くなるよう書き換えましょう.
// apply f n times to x template <class F, class T> constexpr T repeated(F f, unsigned n, T x) { return n == 0 ? x : n == 1 ? f(x) : repeated(f, n / 2, repeated(f, n - n / 2, x)); } constexpr int inc(int x) { return x + 1; } static_assert(repeated(inc, 1000000, 0) == 1000000, "");
$ g++ -c -std=c++0x repeated.cpp