为什么abs(complex< int>)总是返回0? [英] Why does abs(complex<int>) always return zero?
问题描述
与VS2010的以下代码打印 0
,与我的预期相反:
The following code with VS2010 prints 0
, contrary to my expectations:
#include <complex>
#include <iostream>
using namespace std;
int main(void)
{
complex<int> z(20, 200);
cout << abs<int>(z) << endl;
return 0;
}
当类型 double
。
It works fine when the type is double
.
推荐答案
根据C ++ ISO规范,26.2 / 2:
According to the C++ ISO spec, §26.2/2:
为除
float >之外的任何类型实例化模板
complex
code>,double
或long double
未指定。
The effect of instantiating the template
complex
for any type other thanfloat
,double
orlong double
is unspecified.
换句话说,当你实例化 complex< int>
时,编译器可以做任何想做的事情。
In other words, the compiler can do whatever it wants to when you instantiate complex<int>
. The fact that you're getting 0 here is perfectly well-defined behavior from a language perspective.
对于比较 - 在 ideone的gcc版本,这个代码甚至不编译。这是另一个完全有效的选择。
For a comparison - on ideone's version of gcc, this code doesn't even compile. That's another perfectly valid option.
希望这有助于!
这篇关于为什么abs(complex< int>)总是返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!