Why does C++ mandate that complex only be instantiated for float, double, or long double?

前端 未结 2 1530
北恋
北恋 2020-12-15 15:49

According to the C++ ISO spec, §26.2/2:

The effect of instantiating the template complex for any type other than float,

相关标签:
2条回答
  • 2020-12-15 16:01

    You can't properly implement many of the std::complex operations on integers. E.g.,

    template <class T>
    T abs(const complex<T> &z);
    

    for a complex<long> cannot have T = long return value when complex numbers are represented as (real,imag) pairs, since it returns the value of sqrt(pow(z.real(), 2) + pow(z.imag(), 2)). Only a few of the operations would make sense.

    Even worse, the polar named constructor cannot be made reliable without breaking the default constructor and vice versa. The standard would have to specify that "complex integers" are Gaussian integers for them to be of any use, and that one of the constructors is severely broken.

    Finally, how would you like your "complex integer division" served, and would you like a "complex remainder" with that? :)

    Summarizing, I think it would be more sensible to specify a separate gaussian_int<T> type with just a few operations than graft support for integral T onto std::complex.

    0 讨论(0)
  • 2020-12-15 16:16

    Probably for compatibility with the helper functions. For example:

    template<class T> T abs (const complex<T>& x);
    

    If T == int, abs would return int, which would mean a massive loss in precision.

    0 讨论(0)
提交回复
热议问题