在constexpr构造函数中复制数组

NO_*_*AME 6 c++ arrays copy-constructor constexpr c++11

我用constexpr复制构造函数编写了一个类.(这是一个结构,使其更简单.)其中一个字段是一个数组.我也要复制它.

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr[0], foo.arr[1], foo.arr[2], foo.arr[3]},
            bar(foo.bar+1) {}
    int arr[SIZE] = {0, 0, 0, 0};
    int bar = 0;
};
Run Code Online (Sandbox Code Playgroud)

我的版本有效,但不可扩展.如果我改变SIZE,我必须修改构造函数.另外,代码看起来很难看.

是否有更好的方法在构造函数中复制数组?构造函数必须是constexpr.

toh*_*ava 3

您可以使用 std::array。由于它是聚合类型,我相信这会起作用。