C++14 で副作用のある constexpr 関数
今更ながら n3652 読んでいて驚いんたんですが C++14 だと次のように副作用のある constexpr 関数が定義できるようです。
[ソース]
constexpr void increment(int& x){ ++x; } constexpr int func(int x){ int n = x; increment(n); increment(n); increment(n); return n; } constexpr void square(int& x){ x *= x; } struct pixel{ int x; int y; constexpr pixel(int a) : x(a), y(a){ square(x); } }; int main(){ constexpr int n = 0; // increment(n); // error static_assert(func(n) == 3, ""); constexpr pixel p(4); static_assert(p.x == 16, ""); static_assert(p.y == 4, ""); return 0; }
こんな感じで副作用のある constexpr 関数が定義できます。
constexpr な変数を直接渡すことはできませんが、constexpr 関数内で非 constexpr 変数が渡せるようです。
constexpr void という関数が定義ができるあたり狂気を感じますね。