I need to implement algorithm, that recursively calculates the scalar product of two vectors using templates.
There is my code:
#include <iostream>
#include <vector>
template<typename T, int Size>
T scalar_product(const std::vector<T> &a, const std::vector<T> &b)
{
return a[Size - 1]*b[Size - 1] + (scalar_product<T, Size - 1>(a, b));
}
template<typename T>
T scalar_product<T, 0>(const std::vector<T> &a, const std::vector<T> &b) // error!
{
return a[0] * b[0];
}
int main()
{
std::vector<int> a(3, 1);
std::vector<int> b(3, 3);
std::cout << scalar_product<int, 3>(a, b);
return 0;
}
If I use this specialisation T scalar_product<T, 0>(...)
, I get error "'scalar_product' : illegal use of explicit template arguments". But if I remove it like this T scalar_product(...)
compiler report that recursion is going to be infinite (because there is no specialisation, as I understand).
There are a lot of questions of this type here, but I wasn't able to find useful answer. How can I specialize this function without using classes? Thank you beforehand!