Return double or complex<double> from template function
c++, template-argument-deduction, templates
Solution
In C++11, you can use the alternative function declaration syntax:
#include <utility> // for declval
template<class T, class U, class V>
auto operator*(const T a, const matrix<U> A)
-> decltype( std::declval<T>() * std::declval<U>() )
{
//...
}
Problem
I am writing some function templates to overload the `*` operator for a matrix class. I do a lot of work with matrices of type `double` and `complex<double>`. Is it possible to write a single template function that returns the correct type? For example: ``` template<class T, class U, class V> matrix<V> operator*(const T a, const matrix<U> A) { matrix<V> B(A.size(1),A.size(2)); for(int ii = 0; ii < B.size(1); ii++) { for(int jj = 0; jj < B.size(2); jj++) { B(ii,jj) = a*A(ii,jj); } } return B; } ``` I would like the return type `V` to be determined by the natural result of `T*U`. Is this possible? EDIT: A follow-up question that I asked received answers that provide additional information applicable here.