Return double or complex<double> from template function

*爱你&永不变心* 提交于 2020-01-11 06:06:25

问题


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.


回答1:


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>() )
{
   //...
}


来源:https://stackoverflow.com/questions/17870504/return-double-or-complexdouble-from-template-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!