constexpr
は、コンパイル時にオブジェクトを定数として使用できるようになることを理解していますが、これが有益な場合の例は何ですか?私はキーワードをよりよく理解しようとしていますが、なぜそれが必要なのかを説明するコンストラクタで使用すると良い例は見つけられません。なぜコンストラクタでconstexprを使用しますか?
以下の両方の例が動作するので、constexprがコンストラクタに配置されるのはなぜですか?
#include <iostream>
using namespace std;
class Rect
{
public:
constexpr Rect(int width, int height)
: mWidth(width), mHeight(height) {}
constexpr int getArea() const { return mWidth * mHeight; }
private:
int mWidth, mHeight;
};
int main(int argc, char* argv[])
{
constexpr Rect r(8, 2);
cout << r.getArea() << endl; //16
int myArray[r.getArea()]; // OK
return 0;
}
コンストラクタのconstexprのなし::コンストラクタのconstexprので
r.getArea()
が一定でないため、2番目の例では
#include <iostream>
using namespace std;
class Rect
{
public:
Rect(int width, int height)
: mWidth(width), mHeight(height) {}
constexpr int getArea() const { return mWidth * mHeight; }
private:
int mWidth, mHeight;
};
int main(int argc, char* argv[])
{
Rect r(8, 2);
cout << r.getArea() << endl; //16
int myArray[r.getArea()]; // OK
return 0;
}
私のために2番目のものはコンパイルされません:http://coliru.stacked-crooked.com/a/a84bbdd8fb82bb49 – Brian
しかし、constexprは 'getArea()'の両方の例に置かれています。 –
'constexpr'とマークされた関数は、その引数(暗黙の' * this'も含む)が定数式である場合にのみ定数式を返します。 –