This question stems from an answer I received yesterday. For the following function, I am getting the error couldn't deduce template parameter ‘V’
if both T
and U
are std::complex<double>
. If T
and U
are different, the function compiles and works as intended.
template<class T, class U, class V>
auto operator*(const T a, const matrix<U> A) -> decltype(std::declval<T>()*std::declval<U>())
{
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;
}
The usage is as follows:
std::complex<double> a1;
matrix<std::complex<double> > A1;
double a2;
matrix<std::complex<double> > A2;
/* ... */
matrix<std::complex<double> > B1 = a1*A1; // Compiler error
matrix<std::complex<double> > B2 = a2*A2; // Compiles and runs fine.
I should also mention I am compiling with g++ 4.7.3 and C++11 enabled.
EDIT:
A work around that I found is to also supply this function template:
template<class T>
matrix<T> operator*(const T a, const matrix<T> A)
{
matrix<T> 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;
}
With this addition, both cases above compile and run correctly.