I’m trying to implement a zip function. zip‘s parameters are each wrapped<Ti>, where Ti varies from parameter to parameter.
zip takes these wrapped<Ti>s and produces a wrapped<tuple<T1&,T2&,...TN&>>, or in other words a wrapped tuple of references to its parameters. The references should preserve const-ness.
Here’s my first stab at zip with one parameter, which doesn’t work in general:
#include <utility>
#include <tuple>
// implement forward_as_tuple as it is missing on my system
namespace ns
{
template<typename... Types>
std::tuple<Types&&...>
forward_as_tuple(Types&&... t)
{
return std::tuple<Types&&...>(std::forward<Types>(t)...);
}
}
template<typename T>
struct wrapped
{
wrapped(T &&x)
: m_x(std::forward<T>(x))
{}
T m_x;
};
template<typename T>
wrapped<std::tuple<T&&>>
zip(wrapped<T> &&x)
{
auto t = ns::forward_as_tuple(std::forward<T>(x.m_x));
return wrapped<std::tuple<T&&>>(t);
}
int main()
{
wrapped<int> w1(13);
wrapped<int> &ref_w1 = w1;
// OK
zip(ref_w1);
const wrapped<int> &cref_w1 = w1;
// XXX won't compile when passing a const reference
zip(cref_w1);
return 0;
}
Is there a way to implement the general, variadic case with a single version of zip?
Here’s the solution I arrived at:
Having
ziptakeWrappedTypes...instead ofwrapped<T>...isn’t as satisfying a solution, but it works.