namespace detail {
template<class T, class U>
using forwarded_type = std::conditional_t<std::is_lvalue_reference<T>::value,
std::remove_reference_t<U>&,
std::remove_reference_t<U>&&>;
}
template<class T, class U>
detail::forwarded_type<T,U> forward_like(U&& u) {
return std::forward<detail::forwarded_type<T,U>>(std::forward<U>(u));
}
template <typename Vector>
void g(Vector&& v, size_t i) {
f(forward_like<Vector>(v[i]));
}
Demo. Using std::forward
in the implementation automatically prevents you from doing a dangerous forward of rvalue as lvalue.
For your actual use case
I'd like to create vector<T>
from vector<U1>
, vector<U2>
, ...., where
each element T
is constructed from U1, U2, ...
. Each array of
vector<Ui>
could be either &
or &&
, and I'd like the Ui
to be
perfectly forwarded.
this becomes something like
template<class T, class...Vectors>
std::vector<T> make_vector(Vectors&&...vectors){
auto n = std::min({vectors.size()...});
std::vector<T> ret;
ret.reserve(n);
for(decltype(n) i = 0; i < n; ++i)
ret.emplace_back(forward_like<Vectors>(vectors[i])...);
return ret;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…