class 不能有自己的静态 constexpr 成员实例吗?

Can't a class have static constexpr member instances of itself?

这段代码给我 不完整类型 错误。 问题是什么?不允许 class 拥有自己的 静态成员实例 吗? 有没有办法达到同样的效果?

struct Size
{
    const unsigned int width;
    const unsigned int height;

    static constexpr Size big = { 480, 240 };

    static constexpr Size small = { 210, 170 };

private:

    Size( ) = default;
};

A​​ class 允许有一个相同类型的静态成员。然而,一个 class 在它的定义结束之前是不完整的,并且一个对象不能被 定义 具有不完整的类型。您可以声明一个不完整类型的对象,然后在它完整的地方定义它(在class之外)。

struct Size
{
    const unsigned int width;
    const unsigned int height;

    static const Size big;
    static const Size small;

private:

    Size( ) = default;
};

const Size Size::big = { 480, 240 };
const Size Size::small = { 210, 170 };

在此处查看:http://coliru.stacked-crooked.com/a/f43395e5d08a3952

然而,这不适用于 constexpr 成员。

Is there a way to achieve the same result?

"the same result",您是否特别打算 constexpr-ness Size::bigSize::small?在那种情况下,也许这已经足够接近了:

struct Size
{
    const unsigned int width = 0;
    const unsigned int height = 0;

    static constexpr Size big() {
        return Size { 480, 240 };
    }

    static constexpr Size small() {
        return Size { 210, 170 };
    }

private:

    constexpr Size() = default;
    constexpr Size(int w, int h )
    : width(w),height(h){}
};

static_assert(Size::big().width == 480,"");
static_assert(Size::small().height == 170,"");

作为变通方法,您可以使用单独的基 class,在派生 class 中定义常量时,该定义是完整的。

struct size_impl
{
//data members and functions here
    unsigned int width;
    unsigned int height;
};


struct size:  public size_impl
{
//create the constants as instantiations of size_impl
    static constexpr size_impl big{480,240};
    static constexpr size_impl small{210,170};

//provide implicit conversion constructor and assignment operator
    constexpr size(const size_impl& s):size_impl(s){}
    using size_impl::operator=;

//put all other constructors here
};

//test:
constexpr size a = size::big;

如果需要,您可以将基 class 放在单独的命名空间中以隐藏其定义。

代码使用 clang 和 gcc 编译