Well, it's hard to know what type you'd want to end up with, which I suppose is your problem. I'd probably add that as a templatized parameter as well. Or: standard containers like std::vector provide a value_type typedef, so that you can use e.g.
Code:
#include <iostream>
#include <algorithm>
#include <vector>
template <typename VectorType>
inline typename VectorType::value_type dotProduct(const VectorType &one, const VectorType &two) {
typename VectorType::value_type value = 0;
for(typename VectorType::size_type i = 0;
i < std::min(one.size(), two.size()); i ++) {
value += one[i] * two[i];
}
return value;
}
int main() {
std::vector<double> a, b;
a.push_back(1);
a.push_back(3);
b.push_back(1);
b.push_back(0.5);
std::cout << dotProduct(a, b) << std::endl;
return 0;
}
That's pretty ugly. But you get the idea. And if you wanted to be really general you could get even uglier:
Code:
#include <iostream>
#include <algorithm>
#include <vector>
template <typename TypeOne, typename TypeTwo, typename ResultType>
inline ResultType dotProduct(const TypeOne &one, const TypeTwo &two) {
ResultType value = 0;
for(std::size_t i = 0; i < std::min(one.size(), two.size()); i ++) {
value += one[i] * two[i];
}
return value;
}
int main() {
std::vector<double> a, b;
a.push_back(1);
a.push_back(3);
b.push_back(1);
b.push_back(0.5);
std::cout << dotProduct<std::vector<double>, std::vector<double>, double>(a, b) << std::endl;
return 0;
}
I'd definitely suggest that you let the types be inferred whenever possible, e.g. let the return type be the value_type of the first parameter or something. Also you'll notice that my code works for any data type (std::vector, maybe your Vector) that supports an [] operator and .size() and has a value_type. You can make your life easier if you assume a Vector.
Finally: I wouldn't overload a * operator if it has complicated semantics like copying the value type of the first argument. I'd probably call it by a custom name. But that's up to you.