Consider this code:
#include <ranges>
#include <memory>
#include <list>
#include <vector>
template <typename T>
struct A
{
std::vector<T> v;
template <typename U>
A(U &&input) : v(std::from_range, std::forward<U>(input)) {}
};
int main()
{
A<std::unique_ptr<int>> a(std::list{std::unique_ptr<int>{}});
}
It doesn’t compile, as std::from_range
tries to copy the elements instead of moving them. run on gcc.godbolt.org
What is the correct and idiomatic solution here? I want it to automatically move the elements if source range is an rvalue and owns the elements.
I know std::views::as_rvalue
exists, but deciding when to apply it requires a lengthy condition:
- The input range must be an rvalue.
- It must own the elements (
std::borrowed_range<U &> == false
, I assume?)
Sure, I can write out this condition manually, but naively hoped that Ranges has a built-in solution to this problem.