template function that takes Vector T and Vector U and returns the sum of v1[i] * v2[i]

closed account (26q2b7Xj)
This is an exercise I am working on alone. The idea is too get familiar with auto, decltype, and type traits. Assuming C++20 isn't a thing yet with concepts, so the implementation goes:

Is my understanding correct? What can be done better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>
#include <exception>
#include <type_traits>

template <typename T, typename U>
constexpr auto f(const std::vector<T>& vt, const std::vector<U>& vu) -> std::vector<decltype(T{} + U{})>
{
	static_assert(std::is_arithmetic<T>::value || std::is_arithmetic<U>::value, "Must support arithmetic operations.");

	std::vector<decltype(T{} + U{})> sum;

	size_t i{};
	for (; i < vt.size(); ++i)
	{
		if (i == vu.size()) break;

		sum.push_back(vt[i] * vu[i]);
	}

	while (i < vt.size())
		sum.push_back(vt[i++]);

	while (i < vu.size())
		sum.push_back(vu[i++]);

	return sum;
}


- Wouldn't you want the static_assert to and the conditions together?
- The for loop could also drop the break statement if you made the terminating condition be i < vt.size() && i < vu.size()
- push_back can incur extra costs if you need to re-allocate the vector multiple times. I would rather reserve max(vt.size(), vu.size()).
- Names are important. What does "f" mean? Give it a meaningful name. The hard part about naming is when you're dealing with templates of potentially unknown types. The more abstract it is, the harder it is to name. What you're doing isn't exactly a dot product since the remaining elements just get tacked on... so maybe something like "multiply_overlapping"? There's no real correct answer, but it's something to think about, and anything is better than "f".
- The standard library generally prefers the use of iterators over explicitly passing objects of <container type>. What this achieves is a better decoupling of the algorithm from the container type itself.
Last edited on
closed account (26q2b7Xj)
Okay I see some parts that need fixing. I must have misunderstood how to go about adding the multiplied values. I agree with push_back(), should have initialized with the right size. As for the last example, can you show a simple example of how that would look like?
Topic archived. No new replies allowed.