返回double或complex< double>从模板功能 [英] Return double or complex<double> from template function
问题描述
我编写一些函数模板来重载 *
运算符作为矩阵类。我对类型 double
和 complex< double>
的矩阵做了很多工作。是否可以编写一个返回正确类型的模板函数?例如:
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;
}
我想要返回类型 V
由 T * U
的自然结果确定。这是否可能?
I would like the return type V
to be determined by the natural result of T*U
. Is this possible?
EDIT:
=http://stackoverflow.com/q/17888805/2018790>问题,我询问收到的答案提供了此处适用的其他信息。
A follow-up question that I asked received answers that provide additional information applicable here.
推荐答案
在C ++ 11中,您可以使用替代函数声明语法:
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>() )
{
//...
}
这篇关于返回double或complex< double>从模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!