Combine multiple vectors (results of function) into one with template

女生的网名这么多〃 提交于 2019-12-05 10:47:32

Dereferencing a container iterator yields a reference (or a const reference, if the container was const), which is why decltype(*std::begin(op(*std::begin(c)))) yields const U& according to your compiler error (and not U).

You can fix this by either removing the reference again with std::remove_reference (or, if you want to also remove const and volatile, std::remove_cvref), or by just asking the vector for what it actually stores:

decltype(*std::begin(op(*std::begin(c)))) -> typename decltype(op(*std::begin(c)))::value_type

I have gone ahead and removed the unneeded U& ex parameter.

template <typename Container, typename UnaryOperation>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op)
    -> std::vector<typename decltype(op(*std::begin(c)))::value_type> {
  std::vector<typename decltype(op(*std::begin(c)))::value_type> v;
  for (auto& e : c) {
    std::vector<typename decltype(op(*std::begin(c)))::value_type> opv = op(e);
    concat(v, opv);
  }
  return v;  
}

Demo

You can also avoid the triple repetition of the decltype chant by naming it:

template <typename Container, typename UnaryOperation>
using applied_op_t = typename decltype(std::declval<UnaryOperation>()(*std::begin(std::declval<Container>())))::value_type;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!