Can I list-initialize a vector of move-only type?

Edit: Since @Johannes doesn’t seem to want to post the best solution as an answer, I’ll just do it.

#include <iterator>
#include <vector>
#include <memory>

int main(){
  using move_only = std::unique_ptr<int>;
  move_only init[] = { move_only(), move_only(), move_only() };
  std::vector<move_only> v{std::make_move_iterator(std::begin(init)),
      std::make_move_iterator(std::end(init))};
}

The iterators returned by std::make_move_iterator will move the pointed-to element when being dereferenced.


Original answer:
We’re gonna utilize a little helper type here:

#include <utility>
#include <type_traits>

template<class T>
struct rref_wrapper
{ // CAUTION - very volatile, use with care
  explicit rref_wrapper(T&& v)
    : _val(std::move(v)) {}

  explicit operator T() const{
    return T{ std::move(_val) };
  }

private:
  T&& _val;
};

// only usable on temporaries
template<class T>
typename std::enable_if<
  !std::is_lvalue_reference<T>::value,
  rref_wrapper<T>
>::type rref(T&& v){
  return rref_wrapper<T>(std::move(v));
}

// lvalue reference can go away
template<class T>
void rref(T&) = delete;

Sadly, the straight-forward code here won’t work:

std::vector<move_only> v{ rref(move_only()), rref(move_only()), rref(move_only()) };

Since the standard, for whatever reason, doesn’t define a converting copy constructor like this:

// in class initializer_list
template<class U>
initializer_list(initializer_list<U> const& other);

The initializer_list<rref_wrapper<move_only>> created by the brace-init-list ({...}) won’t convert to the initializer_list<move_only> that the vector<move_only> takes. So we need a two-step initialization here:

std::initializer_list<rref_wrapper<move_only>> il{ rref(move_only()),
                                                   rref(move_only()),
                                                   rref(move_only()) };
std::vector<move_only> v(il.begin(), il.end());

Leave a Comment