[英]How to list-initialize a const std::array member using a std::array constructor argument C++
suppose we have the following class in C++11 or later: 假设我们在C ++ 11或更高版本中具有以下类:
class MyClass {
private:
const std::array<SomeType, 100> myArray;
public:
explicit MyClass(std::array<SomeOtherType, 100> initArray);
};
Assuming that class SomeType has a constructor that takes a single SomeOtherType as an argument, is it possible to initialize the const member array using list-initialization in the constructor? 假设类SomeType具有一个采用单个SomeOtherType作为参数的构造函数,是否可以在构造函数中使用列表初始化来初始化const成员数组? What is the syntax for doing so?
这样做的语法是什么?
Clearly, just directly initializing it like this doesn't work: 显然,像这样直接初始化它是行不通的:
MyClass::MyClass(std::array<SomeOtherType, 100> initArray) :
myArray{initArray} {}
Thanks! 谢谢!
You can use a variadic template: 您可以使用可变参数模板:
#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 };
}
Or you can initialize it with an array passed to the constructor: 或者,您可以使用传递给构造函数的数组来初始化它:
#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);
}
But these options don't take into account that you want to have an array of SomeOtherType
converted to an array of SomeType
. 但是这些选项没有考虑到您希望将
SomeOtherType
数组转换为SomeType
数组。 I didn't realize that at first, hece the variants above. 一开始我没有意识到,请注意上面的变体。
#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);
}
You can unpack arguments with std::index_sequence
and delegating constructors 您可以使用
std::index_sequence
解压缩参数并委托构造函数
template<typename Arr, size_t... Is>
MyClass(Arr&& arr, std::index_sequence<Is...>)
: myArray{arr[Is]...} ()
explicit MyClass(std::array<SomeOtherType, 100> arr) : MyClass(arr, std::make_index_sequence<100>{}) ()
This is possible. 这个有可能。 You just need a little helper function template to do the conversion for you.
您只需要一个辅助函数模板即可为您进行转换。 Something like this:
像这样:
template <class T, class U, size_t N>
std::array<T, N> ArrayConvert(std::array<U, N> const& init)
{
std::array<T, N> result;
std::copy(init.begin(), init.end(), result.begin());
return result;
}
class Foo
{
std::array<int, 100> myArray;
public:
template <class U> Foo(std::array<U, 100> const& init)
: myArray(ArrayConvert<int>(init))
{
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.