![](/img/trans.png)
[英]What is the proper way to execute a complex shell command within C++?
[英]What is the proper way to average a set of complex numbers in c++?
我繼承了一些需要平均一些復數的 C++ 代碼。 給定一個集合,它將那些傳遞條件的值添加到累加器,然后除以添加的值的數量。
使用 gcc(當前為 gcc 8)如果我使用獨立operator/
,我會得到template argument deduction/substitution failed
,但它與std::complex::operator/=
一起工作正常。 這種細微差別對於后續維護者來說似乎很脆弱。
那么獲得復數平均值的正確方法是什么?
該語言僅部分支持復數除以整數類型是否合理?
std::complex<double> A[32] = { /* initialization left to the reader */ };
int count = 0;
std::complex<double> sum;
for (auto i = 0; i < 32; ++i) {
if ( i % 2 ) { // arbitrary condition, not important
sum += A[i];
++count;
}
}
auto avg = sum / count; // this is ambiguous
sum /= count; // this is not
(代表性錯誤,好奇)
main.cpp: In function ‘int main()’:
main.cpp:16:16: error: no match for ‘operator/’ (operand types are ‘std::complex<double>’ and ‘int’)
auto avg = sum / count; // this is ambiguous
~~~~^~~~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:434:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const _Tp&, const std::complex<_Tp>&)
operator/(const _Tp& __x, const complex<_Tp>& __y)
^~~~~~~~
/usr/include/c++/7/complex:434:5: note: template argument deduction/substitution failed:
main.cpp:16:18: note: mismatched types ‘const std::complex<_Tp>’ and ‘int’
auto avg = sum / count; // this is ambiguous
^~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:425:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const std::complex<_Tp>&, const _Tp&)
operator/(const complex<_Tp>& __x, const _Tp& __y)
^~~~~~~~
/usr/include/c++/7/complex:425:5: note: template argument deduction/substitution failed:
main.cpp:16:18: note: deduced conflicting types for parameter ‘const _Tp’ (‘double’ and ‘int’)
auto avg = sum / count; // this is ambiguous
^~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:416:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const std::complex<_Tp>&, const std::complex<_Tp>&)
operator/(const complex<_Tp>& __x, const complex<_Tp>& __y)
^~~~~~~~
/usr/include/c++/7/complex:416:5: note: template argument deduction/substitution failed:
main.cpp:16:18: note: mismatched types ‘const std::complex<_Tp>’ and ‘int’
auto avg = sum / count; // this is ambiguous
^~~~~
不確定對其進行除法的最正確方法是什么,但是如果您查看operator/
和operator/=
所有參數,您會注意到:
operator/
接受std::complex<T>
或T
。
double
創建了原始復合體,那么它應該只接受另一個值為double
或complex<double>
。clang
直接給了invalid operands to binary expression ('std::complex<double>' and 'int')
錯誤 operator/=
接受std::complex<T>
或T
,同時也特化了float
、 double
和long double
。
operator/=
任何內容都會被隱式轉換為float
、 double
或long double
,而int
可以這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.