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

自作多情 提交于 2021-02-08 12:37:16

问题


The C++ program

#include <complex>
#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?


回答1:


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*=.




回答2:


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!-)



来源:https://stackoverflow.com/questions/1641819/why-is-complexdouble-int-not-defined-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!