Reputation: 912
It seems that I'm doing here something terribly wrong. Can you help me? The aim is to use inner_product for complex vectors.
#include<iostream>
#include<vector>
#include <numeric>
#include <complex>
using namespace std;
template<class T>
complex< T > complex_prod(complex< T > a, complex< T > b)
{
return conj<T>(a)*b;
}
template<class T>
complex< T > add_c(complex< T > a, complex< T > b)
{
return a+b;
}
int main()
{
complex<double> c1(1.,3.);
complex<double> c2(2.,4.);
vector<complex<double> > C1(3,c1);
vector<complex<double> > C2(3,c2);
cout<<inner_product(C1.begin(),C2.end(),C2.begin(),0.,add_c<double>,complex_prod<double>) <<endl;
return 0;
}
I don't see why there is a conversion problem, everything seems to be defined and the iteration should make no problem.
Upvotes: 1
Views: 3129
Reputation: 227418
The problem is that inner_product
needs to know the type of the initial value, so you need to pass it an std::complex
instead of a 0.
:
inner_product(C1.begin(),C2.end(),C2.begin(),std::complex<double>(0.,0.),add_c<double>,complex_prod<double>);
or simply,
inner_product(C1.begin(),C2.end(),C2.begin(),std::complex<double>(),add_c<double>,complex_prod<double>);
Although an std::complex<double>
can be implicitly constructed from a single numeric type
std::complex<double> c = 2.*4.*300;
the inner_product
template looks like
template<
class InputIterator1,
class InputIteratorr2,
class T,
class BinaryOperation1,
class BinaryOperation2
> T inner_product( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, T value,
BinaryOperation1 op1,
BinaryOperation2 op2 );
so there is a template parameter for the value
. So there is no way the compiler can know you mean std::complex<double>
here, it just interprets 0.
as double
.
Upvotes: 3