【问题标题】:Why would you use a constexpr on a constructor?为什么要在构造函数上使用 constexpr?
【发布时间】:2016-04-07 23:44:07
【问题描述】:

我知道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:

#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;
}

【问题讨论】:

  • 第二个无法为我编译:coliru.stacked-crooked.com/a/a84bbdd8fb82bb49
  • 但是 constexpr 被放置在 getArea() 的两个示例中。
  • 标记为constexpr 的函数仅在其参数(包括隐含的*this)也是常量表达式时才返回常量表达式
  • @Brian clang 接受代码。我发起了new question 寻求帮助

标签: c++ constexpr


【解决方案1】:

在第二个示例中,标准 C++ 中不允许使用 int myArray[r.getArea()];,因为 r.getArea() 不是常量表达式。 (如果您的编译器接受它,那么您依赖于编译器扩展,并且如果您以一致模式调用编译器,则应该产生警告)。

如果将数组更改为:

std::array<int, r.getArea()> myArray;

编译器不太可能在非constexpr 版本中接受。

【讨论】:

  • 嗯,这真的没有解决我的问题,但你基本上是说你只会在构造函数上使用constexpr,该构造函数将生成一个需要用作的对象编译时的文字?
  • @EavenSheets 您问“下面的两个示例都有效,那么为什么将 constexpr 放在构造函数上?” .我通过展示您的第二个示例实际上不起作用来解决这个问题,并将 constexpr 放在构造函数上使其工作。 “为什么要在构造函数上使用 constexpr?”回答为“如果您希望该类的对象能够用于生成常量表达式”。
  • 这不能回答问题。
  • @LightnessRacesinOrbit 我认为确实如此。如果您不同意,也许您可​​以发布自己的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 2018-06-02
  • 2013-12-24
相关资源
最近更新 更多