Question

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.

Was it helpful?

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>() )
{
   //...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top