一个类不能有自己的静态 constexpr 成员实例吗?

问题描述 投票:0回答:4

这段代码给我 incomplete type 错误。 问题是什么?不允许一个类拥有自己的静态成员实例吗? 有没有办法达到同样的结果?

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;
};
c++ c++11 constexpr static-members incomplete-type
4个回答
64
投票

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

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
成员。


46
投票

有没有办法达到同样的效果?

通过“相同的结果”,您是否特别打算

constexpr
-ness
Size::big
Size::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,"");

6
投票

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

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;

如果你愿意,你可以将基类放在一个单独的命名空间中以隐藏它的定义。

代码用 clang 和 gcc 编译


0
投票

另一种可能的解决方法是使用模板来延迟对

size
定义的需求。

template<typename...>
class size {
public:
    template<typename...>
    static constexpr auto big = size{480, 240};

    template<typename...>
    static constexpr auto small = size{210, 170};

    unsigned const width;
    unsigned const height;

private:
    constexpr size() = default;
    constexpr size(unsigned w, unsigned h)
        : width{w}, height{h} {}
};

static_assert(noexcept(size<>::big<>), "");

实例

© www.soinside.com 2019 - 2024. All rights reserved.