So I just learned (thanks guys) about decltype. I now can write really nice vector templates that actually outperform valarrays(!):
template <typename T, typename U>
vector<decltype(T()*U())> operator*(const vector<T>& A, const vector<U>& B){
vector<decltype(T()*U())> C = vector<decltype(T()*U())>(A.size());
typename vector<T>::const_iterator a = A.begin();
typename vector<U>::const_iterator b = B.begin();
typename vector<decltype(T()*U())>::iterator c = C.begin();
while (a!=A.end()){
*c = (*a) + (*b);
a++; b++; c++;
}
return C;
}
Is it possible to make this kind of templating even more “meta”, in the sense that we allow the operator (“*”) itself to be a template parameter? I.e. have one single template definition that works for *, +, %, etc, where the appropriate operator op is used in *c = (*a) op (*b)?
I’m betting it is not, but it would be nice!
As you expected, this answer is “no.” 🙂
However, you can use the preprocessor to generate such functions: