Search code examples
c++templatesrvalue-reference

Perfect forwarding with template classes


Suppose I have a template class, for example template<int n, int m> class Matrix

Is there a way to define a matrix multiplication operator * so that

  1. the arguments to * can be either lvalues or rvalue references
  2. *infers the appropriate return type (i.e. the appropriate template parameters) from its arguments

What I have in mind is something like

template< int n,int k, int m, template<int,int> class T1, template<int, int> class T2, template<int,int>class T3 >
 T3<n,m> operator*(T1<n,k>&&, T2<k,m>&&)//does not work

When I try to run the above code (with the bodies filled in in the obvious ways), I get an error:

Cannot convert from Matrix<1,1> to Matrix<1,1>&&

when the arguments are lvalues.


Solution

  • Yes. From my own code:

    template
    <
        int LeftColumnsRightRows, int LeftRows,
        int RightColumns
    >
    Matrix<RightColumns, LeftRows> operator*(Matrix<LeftColumnsRightRows, LeftRows> const& a, Matrix<RightColumns, LeftColumnsRightRows> const& b)
    

    And I don't know why you'd want it to take &&s. If you want to convert two other types to matrices and then multiply them, you should do the conversion outside of the multiplication operator.