「C++の基礎 - constexpr」の版間の差分

ナビゲーションに移動 検索に移動
(ページの作成:「== 概要 == C++には、<code>constexpr</code>という概念がある。<br> <br> * constexprが使用できない、または、使用すべきではない場合 **…」)
 
265行目: 265行目:
   
   
     std::cout << /* a << ", " << */ b << ", " << c << std::endl;
     std::cout << /* a << ", " << */ b << ", " << c << std::endl;
    return 0;
}
</source>
===== メンバ関数のconstexpr =====
メンバ関数にもconstexprを付けることができる。<br>
付ける基準は先ほどと同様、「コンパイル時に計算できるかどうか」である。<br>
<source lang="c++">
class CHoge
{
    // ...
    public:
    // ...
    auto f(int x, ...) { ... };
};
</source>
を、以下のように考えれば、constexprを付けるかどうかが判断できる。
<source lang="c++">
class C {...};
auto f(C& this, int x, ...) { ... };
</source>
<br>
<source lang="c++">
#include <iostream>
class CHoge
{
    private:
      int a;
    public:
      CHoge() = default;
      constexpr CHoge(int a): a(a) {} // メンバ変数の初期化もコンパイル時に可能
      // コンパイル可能  コンパイル時に計算可能
      constexpr auto get() const
      {
          return a;
      }
      // コンパイル可能  コンパイル時に計算可能
      constexpr auto add(const int b)
      {
          a += b;
          return a;
      }
      constexpr auto print() const
      {
          // std::cout << a << std::endl; // コンパイルエラー  コンパイル時に標準出力への出力はできない
          return a;
      }
};
constexpr auto use_add(int a)
{
    auto c = CHoge(a);
    c.add(42);
    return c;
}
int main()
{
    constexpr auto c = CHoge(42);
    std::cout << c.get() << std::endl;
    constexpr auto c2 = use_add(42);
    std::cout << c2.get() << std::endl;
    c2.print();
   
   
     return 0;
     return 0;

案内メニュー