Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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

The effect of instantiating the template complex for any type other than float, double or long double is unspecified.

Why would the standard authors explicitly add this restriction? This makes it unspecified, for example, what happens if you make complex<int> or a complex<MyCustomFixedPointType> and seems like an artificial restriction.

Is there a reason for this limitation? Is there a workaround if you want to instantiate complex with your own custom type?

I'm primarily asking this question because of this earlier question, in which the OP was confused as to why abs was giving bizarre outputs for complex<int>. That said, this still doesn't quite make sense given that we also might want to make complex numbers out of fixed-points types, higher-precision real numbers, etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...