Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c++ - Perfect forwarding container element

Similar to this question, but instead of perfect forwarding member of an object, I would like to know how to perfect forwarding elements of an STL container, i.e. similar to

struct X {};
void f(X&);
void f(X&&);

template <typename Vector>
void g(Vector&& v, size_t i) {
  if (is_lvalue_reference<Vector>::value) {
    f(v[i]);
  } else {
    f(move(v[i]));
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...