implementing a variadic zip function with const-correctness

限于喜欢 提交于 2019-11-30 22:35:43
Nicol Bolas

Admittedly, I don't have a C++0x compiler that handles variadic templates, so I can't test it. But this might do the trick.

template<typename T>
    struct wrapped
{
    wrapped(T &&x)
    : m_x(std::forward<T>(x))
    {}

    typedef T type;

    T m_x;
};

template<typename... Types>
    wrapped<std::tuple<Types&&...>> zip(wrapped<Types>&&... x)
{
    return wrapped<std::tuple<Types&&...>>(std::tuple<Types&&...>(std::forward<Types>(x.m_x)...));
}

I'm not entirely sure if it is legal to call zip like this:

zip(wrapped<T1>(value1), wrapped<T2>(value2));

You may have to explicitly qualify the call:

zip<T1, T2>(wrapped<T1>(value1), wrapped<T2>(value2));

Here's the solution I arrived at:

#include <utility>
#include <tuple>
#include <cassert>

template<typename T>
  struct wrapped
{
  wrapped(T &&x)
    : m_x(std::forward<T>(x))
  {}

  T m_x;
};

template<typename Tuple>
  wrapped<Tuple> make_wrapped_tuple(Tuple &&x)
{
  return wrapped<Tuple>(std::forward<Tuple>(x));
}

template<typename... WrappedTypes>
  decltype(make_wrapped_tuple(std::forward_as_tuple(std::declval<WrappedTypes>().m_x...)))
    zip(WrappedTypes&&... x)
{
  return make_wrapped_tuple(std::forward_as_tuple(x.m_x...));
}

int main()
{
  wrapped<int> w1(1);
  wrapped<int> w2(2);
  wrapped<int> w3(3);
  wrapped<int> w4(4);

  auto z1 = zip(w1,w2,w3,w4);

  z1.m_x = std::make_tuple(11,22,33,44);

  assert(w1.m_x == 11);
  assert(w2.m_x == 22);
  assert(w3.m_x == 33);
  assert(w4.m_x == 44);

  const wrapped<int> &cref_w1 = w1;

  auto z2 = zip(cref_w1, w2, w3, w4);

  // does not compile, as desired
  // z2.m_x = std::make_tuple(111,222,333,444);

  return 0;
}

Having zip take WrappedTypes... instead of wrapped<T>... isn't as satisfying a solution, but it works.

T-Magic
template<typename T>
    struct wrapped
{
    wrapped(T &&x)
    : m_x(std::forward<T>(x))
    {}

    typedef T type;

    T m_x;
};

template<typename... Types>
    wrapped<std::tuple<T&&...>> zip(wrapped<Types>... &&x)
{
    return G+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!