4

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.

Community
  • 1
  • 1
OSE
  • 986
  • 2
  • 13
  • 19
  • This could probably be done with C++11 - do you have access to this, or are you using an older version? – wlyles Jul 25 '13 at 23:35
  • I do have access to C++11 through g++ 4.7.3. It appears that this standard is still experimental for this compiler. The answer by @jrok works for me. Is support for C++11 features expected to improve over time or are any of these features at risk of disappearing? – OSE Jul 25 '13 at 23:45
  • @OSE: There is no compiler that don't only have experimental support for C++11. There will be no changes in the C++11 support that will lead to break your code. – Kyle_the_hacker Jul 25 '13 at 23:49
  • Features get deprecated, but never completely disapear (the only exception I know is invalid conversion from string literals to `char*` which was deemed invalid in C++11). You're safe with this. It even gets better, in C++14, you'll be able to emit the decltype part when not needed and let functions deduce the return type by themselves (with some restrictions, I think). – jrok Jul 25 '13 at 23:50

1 Answers1

4

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>() )
{
   //...
}
jrok
  • 54,456
  • 9
  • 109
  • 141