How to initialize std :: array <T, 2> where T is not copied and is not standard?
I have a fixed number of objects of class T that are not copied and are not standard. Since the size is fixed, I would like to use a container like array-ish, like std::array instead of unique_ptr or vector . I would like to avoid an extra layer of indirection if I can help him.
How to initialize std::array<T, 2> ? Using array<T, 2> {T(...), T(...)} results in an error about the remote copy instance. Using array<T, 2> {move(T(...)), move(T(...))} does not force array elements to use the move constructor. If std::array<T, 2> does not inherently work, what else can I do without resorting to an additional layer of indirect or manual memory management methods such as layout-new?
No additional material is needed, just initialize it directly:
class Foo { public: Foo() = delete; Foo(int,char) {} Foo(Foo const &) = delete; Foo & operator = (Foo const &) = delete; }; std::array<Foo, 2> arr {{ {1, '1'}, {2, '2'} }}; My example is not the best, but it works. Just create a function that make_array and make_array for you.
#include <array> #include <iostream> class Foo { public: Foo(int) { } Foo(const Foo &) = delete; Foo(Foo &&) { std::cout<<"Moved\n"; } }; template<class... Type> constexpr std::array<typename std::common_type<Type...>::type, sizeof...(Type)> make_array(Type&&... t) { return {std::forward<Type>(t)...}; } int main() { auto arr = make_array(Foo{1}, Foo{2}); return 0; } As pointed out in the comments, you can do std::array<Foo, 2> arr = {Foo{1}, Foo{2}} .
I noticed that you tried to move in your post. Are you sure your class is moveable ?