c++ - 如何使用 std::array 构造函数参数 C++ 列表初始化 const std::array 成员

标签 c++ constructor constants stdarray list-initialization

假设我们在 C++11 或更高版本中有以下类:

class MyClass {
private:
    const std::array<SomeType, 100> myArray;
public:
    explicit MyClass(std::array<SomeOtherType, 100> initArray);
};

假设类 SomeType 有一个以单个 SomeOtherType 作为参数的构造函数,是否可以在构造函数中使用列表初始化来初始化 const 成员数组?这样做的语法是什么?

很明显,像这样直接初始化它是行不通的:

MyClass::MyClass(std::array<SomeOtherType, 100> initArray) :
    myArray{initArray} {}

谢谢!

最佳答案

您可以使用可变参数模板:

#include <array>

struct foo
{
    const std::array<int, 10> bar;

    template<typename... T>
    foo(T&&... t)
    : bar({ std::move(t)... })
    {}
};

int main()
{
    foo f{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}

或者您可以使用传递给构造函数的数组对其进行初始化:

#include <array>

struct foo
{
    const std::array<int, 10> bar;

    explicit foo(std::array<int, 10> const &qux)
    : bar{ qux }
    {}
};

int main()
{
    std::array<int, 10> qux;
    foo f(qux);
}

但是这些选项没有考虑到您希望将 SomeOtherType 数组转换为 SomeType 数组。起初我没有意识到这一点,所以注意到上面的变体。

#include <cstddef>
#include <array>
#include <utility>

struct SomeOtherType{};

struct SomeType {
    SomeType(SomeOtherType) {}
};

struct MyClass
{
    const std::array<SomeType, 100> myArray;

    template<typename T, std::size_t... N>
    MyClass(T&& qux, std::index_sequence<N...>)
    : myArray{ qux[N]... }
    {}

    explicit MyClass(std::array<SomeOtherType, 100> const &qux)
    : MyClass{ qux, std::make_index_sequence<100>{} }
    {}
};

int main()
{
    std::array<SomeOtherType, 100> qux{};
    MyClass foo(qux);
}

关于c++ - 如何使用 std::array 构造函数参数 C++ 列表初始化 const std::array 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492474/

相关文章:

c++ - 如何在调用 SelectItem 函数时强制 CTreeCtrl 不滚动到项目?

c++ - 从属于同一类的对象内部访问类变量

c++ - 使用 C++ 计算多行注释之间的所有行

class - ":"在 dart 的类构造函数中意味着什么?

c++ - 带空括号的默认构造函数

c++ - 如何在 C++ 中将 int 参数放入 Sigleton 构造函数

c - 定义数组时出错,即使它是通过常量设置的

c++ - 在 Windows 上的服务器应用程序中使用隐藏窗口是否可以接受?

c++ - 数组初始化在 C++ 中使用 const 变量

c# - 有什么理由为常量计算 INT 吗?