gpt4 book ai didi

c++ - 使用 complex 的函数式转换的模糊转换

转载 作者:太空狗 更新时间:2023-10-29 20:23:36 24 4
gpt4 key购买 nike

我有一个 MVE 程序可以用 g++-5.2.0 编译和运行,但不能用 clang-602.0.53 编译和运行。该程序尝试将 lambda 表达式分配给兼容类型的类型别名。

#include<iostream>
#include<complex>

using std::cout;
using std::endl;
using std::complex;
// type alias
using CfDD = complex<double> (*) (double);
// lambda of compatible type
auto theLambda = [] (double _) {return complex<double>({1,0});};

int main()
{ // Show that the lambda is callable:
cout << theLambda(3.14) << endl;
// Show that the lambda is assignable to a var of type CfDD
CfDD cfdd = theLambda;
cout << cfdd (3.14) << endl;
}

此程序在使用 g++-5.2.0 编译时有效:

$ g++-5 --version
g++-5 (Homebrew gcc 5.2.0) 5.2.0
...
$ g++-5 -std=c++14 main.cpp && ./a.out
(1,0)
(1,0)

但是会产生一个我不明白也不知道如何在 clang 下修复的错误:

$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with- gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
...

$ gcc -std=c++14 main.cpp

main.cpp:10:40: error: ambiguous conversion for functional-style cast from 'void' to
'complex<double>'
auto theLambda = [] (double _) {return complex<double>({1,0});};
^~~~~~~~~~~~~~~~~~~~~
... candidate is the implicit move constructor
class _LIBCPP_TYPE_VIS_ONLY complex<double>
^
... candidate is the implicit copy constructor
candidate constructor
complex<double>::complex(const complex<float>& __c)

这个错误是什么意思,为什么这段代码不能编译?

最佳答案

当你写的时候:

return complex<double>({1,0});

我们查看 std::complex<double> 的有效构造函数并找到:

constexpr complex(double re = 0.0, double im = 0.0); // (1)

constexpr complex( const complex& other ); // (2)

constexpr complex(const complex<float>& other); // (3a)
explicit constexpr complex(const complex<long double>& other); // (3b)

我们正在用初始化列表构造这个对象。所以(1)不可行,(3b) 也不可行因为该构造函数被标记为 explicit .然而,另外两个都是可行的,因为两者都是 complex<double>complex<float>可以由两个 int 构成秒。两者都不比另一个好,这就是 clang 提示“模棱两可的转换”的原因。

最简单的解决方案是删除不必要的 {}小号:

return complex<double>(1,0);

请注意,您不需要将参数命名为 _ ,您可以不为其提供名称。

关于c++ - 使用 complex<double> 的函数式转换的模糊转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com