マッピィ Techlog

日々思うこと

【C++】constexprについて

(Effective Modern C++ 項目10を読んで、知らなかったこと)
constexprについてメモ。

・constexpr指定された変数はコンパイル時に定数になる。
・関数にも適用できる。その際、引数かconstでしか決まらない結果であることが条件。

(gcc7.2.0)
static const int test = 0;    // constなのでOK
constexpr int func(int a)
{
    return a + test;
}
int main()
{
    constexpr int a = func(1);
    std::cout << a << std::endl;
}

Effective Modern C++ ―C++11/14プログラムを進化させる42項目

Effective Modern C++ ―C++11/14プログラムを進化させる42項目