用另一个数组初始化对象的 const 数组

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

想象我有以下课程:

class Foo
{
public:
    Foo(int a) : a_(a) { }
    
private:
    int a_;
};

我还有以下数组:

std::array<int, 5> as = { 1, 8, 3, 0, 12 };

现在我想创建一个 Foo 的常量数组,其中 as 作为参数,如下所示:

const std::array<Foo, 5> foos( as );

这可能吗?如果是的话,怎么办?

c++ arrays object constants
1个回答
0
投票

如果向

Foo
添加默认构造函数,则可以使用立即调用的 lambda 和
std::transform
std::identity
的组合:

#include <algorithm>
#include <array>

class Foo
{
public:
    Foo() = default;
    Foo(int a) : a_(a) { }

private:
    int a_;
};

int main() {
    std::array<int, 5> as = { 1, 8, 3, 0, 12 };
    const std::array<Foo, 5> foos =
        [&]() -> auto
        {
            std::array<Foo, 5> foos_tmp;
            std::transform(as.begin(), as.end(), foos_tmp.begin(), std::identity{});
            return foos_tmp;
        }();
};

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