我正在编写一些函数模板来重载 *
矩阵类的运算符。我用 double
类型的矩阵做了很多工作和 complex<double>
.是否可以编写一个返回正确类型的模板函数?例如:
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
的自然结果决定.这可能吗?
编辑:
后续 question我提出的问题收到的答案提供了适用于此处的额外信息。
最佳答案
在 C++11 中,您可以使用替代函数声明语法:
#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>() )
{
//...
}
关于c++ - 从模板函数返回 double 或 complex<double>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17870504/