I can initialize a struct with a single std::array
element using a variadic template constructor:
#include <array>
#include <initializer_list>
#include <memory>
struct Foo {
using data_type = int;
using foo_type = std::array<data_type,2>;
using init_type = std::initializer_list<data_type>;
template <typename... T> Foo(T... array) : array_{array...} {}
foo_type array_;
};
int main() {
Foo foo {1,2}; // this works
std::unique_ptr<Foo> foo2 = std::make_unique<Foo>(3,4); // this also works!
return 0;
}
This works fine! But how can I do the initialization if I have more than a single array member in Foo
?
I tried the following which does not work:
#include <array>
#include <initializer_list>
#include <memory>
struct Foo {
using data_type = int;
using foo_type = std::array<data_type,2>;
using init_type = std::initializer_list<data_type>;
template <typename T> Foo(T array1, T array2)
: array1_{init_array(array1)}, array2_{init_array(array2)} {}
template <typename... T> constexpr auto init_array(T... array) {
return array...;
}
foo_type array1_, array2_;
};
int main() {
Foo foo {{1,2},{3,4}};
return 0;
}
This gives an error:
test.cpp: In member function ‘constexpr auto Foo::init_array(T ...)’:
test.cpp:12:16: error: parameter packs not expanded with ‘...’:
12 | return array...;
| ^~~~~