假设我们在 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/