以下代码可以正常编译g++ (GCC) 4.7.1 20120721
, 但
最近构建失败clang version 3.2 (trunk)
.
struct Y {};
struct X {
operator const Y() const { return Y(); }
};
void f(Y&& y) {}
int main()
{
f(X());
return 0;
}
将转换运算符更改为operator Y() const
足够了
使代码在两个编译器上都可以编译。
在这种情况下,哪个编译器实际上符合标准?什么是
标准实际上是这么说的吗?
按要求逐字错误:
bla.cpp:14:5: error: no viable conversion from 'X' to 'Y'
f(X());
^~~
bla.cpp:1:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'X' to
'const Y &' for 1st argument
struct Y {
^
bla.cpp:1:8: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'X' to
'Y &&' for 1st argument
struct Y {
^
bla.cpp:6:3: note: candidate function
operator const Y() const { return Y(); }
^
bla.cpp:10:12: note: passing argument to parameter 'y' here
void f(Y&& y) {}
^
EDIT:不幸的是,即使添加了过载
void f(const Y&) {}
仍然让 clang 选择右值引用重载,所以这
破坏了过去可以正常编译的现有代码,例如与标准
容器。
我相信 clang 拒绝这一点是正确的。将参数传递给f(Y&&)
需要两个转换步骤,第一个是您的operator const Y()
第二个是Y
的复制构造函数。我认为两者都算作用户定义的转换,并且都是隐式的,这违反了隐式转换序列仅包含一个用户定义的转换的原则。
This 按const值返回的目的? https://stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value包含一些关于返回 a 的语义的有趣见解const T
.
嗯,如果我尝试添加一个重载void f(const Y&y)
正如现在编辑的问题一样,clang 的行为非常奇怪。它仍然抱怨无法转换X
to Y
,甚至没有列出过载f(const Y& y)
在其诊断中。但是一旦我改变了过载Y
按值,即写void f(const Y y)
,它抱怨调用f
模棱两可。
这是 XCode 4.5 的 clang 报告Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
。如果您可以使用 vanilla clang 重现此内容,您可能应该在 clang 邮件列表上报告此内容 - 当然似乎那里潜伏着一个错误某处...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)