其他分享
首页 > 其他分享> > c – 完美的转发容器元素

c – 完美的转发容器元素

作者:互联网

类似于this question,但我不想完成一个对象的转发成员,我想知道如何完善STL容器的转发元素,即类似于

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]));
  }
}

解决方法:

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.在实现中使用std :: forward会自动阻止你将rvalue作为左值进行危险的前进.

对于您的实际用例

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.

这变得像

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;
}

标签:perfect-forwarding,c,c11
来源: https://codeday.me/bug/20190929/1832611.html