本文介绍了为什么C ++要求这个复合体只实例化float,double或long double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++ ISO规范,  26.2 / 2:

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

为什么标准作者明确添加此限制?这使得它未指定,例如,如果你使 complex< int> complex< MyCustomFixedPointType> 似乎是一种人为的限制。

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.

有这个限制的原因吗?如果你想用你自己的自定义类型来实例化 complex ,是否有解决方法?

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

问题,因为,其中OP被弄糊涂了为什么 abs 给出 complex< int> 的奇怪输出。也就是说,考虑到我们也可能想要从固定点类型,更高精度的实数等中创建复杂数字,这还是没有意义。 / p>

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.

推荐答案

您不能正确实现许多 std :: complex 对整数的操作。例如,

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

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

对于复杂< long> T = long 当复数表示为(real,imag)对时的返回值,因为它返回 sqrt(pow (),2)+ pow(z.imag(),2))

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? :)

总而言之,我认为指定一个单独的 gaussian_int< T> 几个操作比移植支持整合 T std :: complex

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.

这篇关于为什么C ++要求这个复合体只实例化float,double或long double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 10:48