C++0x - constexpr

コンパイル時に実行される関数を定義できる
これによって、関数の戻値をコンパイル時定数にできる



いままで再帰テンプレートやクラステンプレートの特殊化で処理していたものが
関数テンプレートの特殊化でできるようになるようだ



いままで

template <class T>
struct is_pointer {
    static const bool value = false;
};

template <class T>
struct is_pointer<T*> {
    static const bool value = true;
};


static_assert(is_pointer<int*>::value, "not pointer");

これから

template <class T>
constexpr bool is_pointer(T*)
{
    return true;
}

template <>
constexpr bool is_pointer(...)
{
    return false;
}

int *p;
static_assert(is_pointer(p), "not pointer");


浮動小数点数の計算もコンパイル時にできるようになりますね

constexpr double circle_area(double radius)
{
    return radius * radius * 3.14;
}

double area = circle_area(3); // コンパイル時定数

いろいろと制限があるとかないとか


ところで、constexprの読み方は、「こんすとえくすぷれっしょん」でいいのだろうか



N2235 Generalized Constant Expressions(日本語訳)

C++0x言語拡張まとめ