开发者

Why is complex<double> * int not defined in C++?

The C++ program

#include <comple开发者_JAVA百科x>
#include <iostream>

int main()
{
  std::complex<double> z(0,2);
  int n = 3;
  std::cout << z * n << std::endl;
}

yields an error: no match for ‘operator*’ in ‘z * n’. Why?

I'm compiling with g++ 4.4.1. Perhaps the compiler is just following the C++ standard, in which case my question is: why does the standard not allow this?


This works:

#include <complex>
#include <iostream>

int main()
{
    std::complex<double> z(0,2);
    double n = 3.0; // Note, double
    std::cout << z * n << std::endl;
}

Because complex is composed of doubles, it multiplies with doubles. Looking at the declaration:

template <typename T>
inline complex<T> operator*(const complex<T>&, const T&);

(The following is thanks to dribeas) The compiler is not allowed to make implicit type conversions during template deduction, so by passing a complex with T being double, and then another T being int, when trying to match the function treating T as double causes the second argument to mis-match, and vice-versa.

For what you want to work, it would have to have a function defined similar to this:

template <typename T, typename U>
inline std::complex<T> operator*(std::complex<T> lhs, const U& rhs)
{
    return lhs *= rhs;
}

Which allows the function to take differing types, which allows the cast to be done when calling operator*=.


std::complex<T>'s operators are defined to take as their arguments other complex<T> instances. The route from an int via a double to a complex<double> is just marginally too contorted / convoluted for the C++ language to follow it according to the standard (and with the huge complications already arising from free-wheeling conversions and cohercions it's hard to criticize that aspect of the standard). I guess the super-special case of complex<double> allowing uncasted ints as operands to its operators was just not deemed frequent and important enough to warrant specifying template specializations for that extremely individual case, considering how trivially easy it is for the programmer to cast the int to double when that's what they actually want!-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜