[英]How to list-initialize a const std::array member using a std::array constructor argument C++
假設我們在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);
}
您可以使用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>{}) ()
這個有可能。 您只需要一個輔助函數模板即可為您進行轉換。 像這樣:
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.