#Template Interview Question

1 messages ยท Page 1 of 1 (latest)

chrome lintelBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

sour rapids
#

What standard of C++ would this be targeting?

#

(also I assume that's meant to be template <typename... vectors> given the usage example?)

green path
#

Up to 20, and yes sorry

sour rapids
#

The obvious approach (valid since ~C++11) would be a recursive helper template, along the lines of ```cpp
template <int... I> struct Vector;

namespace detail {
template <typename... Vs> struct multiply_vectors;

// base cases
template <typename V> struct multiply_vectors<V> {
using type = V;
};
template <int... I1, int... I2> struct multiply_vectors<Vector<I1...>, Vector<I2...>> {
using type = Vector<(I1 * I2)...>;
};

// recursive case
template <typename V1, typename V2, typename... Rest> struct multiply_vectors<V1, V2, Rest...> {
using type = typename multiply_vectors<typename multiply_vectors<V1, V2>::type, Rest...>::type;
};
}

template <typename... Vs>
struct zip {
using type = typename detail::multiply_vectors<Vs...>::type;
};

// ...

static_assert(std::is_same<zip<Vector<1, 2, 3>, Vector<4, 5, 6>, Vector<7, 8, 9>>::type, Vector<28, 80, 162>>::value);

#

a more fancy version since C++17 (that's potentially better compile times) would be to use an operator* overload + fold expressions and decltype

green path
#
using type = Vector<(I1 * I2)...>;

How did I not know you could do this ๐Ÿคฆโ€โ™‚๏ธ

sour rapids
#
template <int... I> struct Vector;

namespace detail {
  template <typename V> struct multiply_helper { using underlying = V; };
  template <int... I1, int... I2>
  auto operator*(multiply_helper<Vector<I1...>>, multiply_helper<Vector<I2...>>)
    -> multiply_helper<Vector<(I1 * I2)...>>;
};

template <typename... Vs>
struct zip {
  using type = typename decltype((... * detail::multiply_helper<Vs>{}))::underlying;
};

// ...

static_assert(std::is_same<zip<Vector<1, 2, 3>, Vector<4, 5, 6>, Vector<7, 8, 9>>::type, Vector<28, 80, 162>>::value);
green path
#

These both work. Thank you wreien

sour rapids
#

again, could simplify if you're allowed to change the definition of Vector itself perhaps

#

but you get the idea ๐Ÿ™‚

green path
#

How do I give you points for solving it? Is that still a thing? I haven't been on here for a while haha

#

!solved

chrome lintelBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

sour rapids
#

I think that was a meme thing during april fools ๐Ÿ˜›

green path
#

Lmao

#

Thank you again!