How can I combine the following two functions into one? Is there something similar to std::forward, but for ranges?
#include <ranges>
#include <vector>
#include <algorithm>
template<class RangeIn, class RangeOut>
void moveOrCopy(RangeIn& from, RangeOut& to)
{
std::ranges::copy(from, std::back_inserter(to));
}
template<class RangeIn, class RangeOut>
requires std::is_rvalue_reference_v<RangeIn&&>
void moveOrCopy(RangeIn&& from, RangeOut& to)
{
std::ranges::move(from, std::back_inserter(to));
}
void test()
{
std::vector<int> a, b;
moveOrCopy(a, b); // copy
moveOrCopy(std::move(a), b); // move
}
There is std::ranges::forward_range, but that's related to forward_iterator, not perfect forwarding.
Handy tool with the above code: https://cppinsights.io/s/45c86608
Intuitive reference for C++ references: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers
a
is a range, but so isstd::ranges::views::all(a)
. You would want to move those under totally different conditions. – Freemasonrystd::vector
, but not for views, for instance. @n.m.couldbeanAI's comment probably is referring to the same thing. – Mushy!borrowed_range<RangeIn>
instead: godbolt.org/z/TEhdro968 – Mournful