我很惊讶地发现以下编译:
struct C { operator C&&() { std::cerr << "ref'd\n"; throw std::runtime_error("what is happening?"); } };
具有自身r值引用转换的运算符的类型.但是,我不能让操作符使用我认为可以做的.将值传递给引用rvalue引用的函数失败,并且在对象上调用std :: move不会触发任何内容.
为什么这个代码可以编译,而且有什么办法可以实现这个功能来运行吗?
clang给出警告:将’C’转换为自身的转换函数将永远不会在类型上使用或不使用引用.
解决方法
struct C { operator C() { } };
也被允许并给出相同的警告.在§12.3.2/ 1中提及:
A conversion function is never used to convert a (possibly
cv-qualified) object to the (possibly cv-qualified) same object type
(or a reference to it),to a (possibly cv-qualified) base class of
that type (or a reference to it),or to (possibly cv-qualified) void.
换句话说,这不是禁止的,但根本不做任何事情. Yakk和Wintermute已经显示了成员函数调用语法的示例,但cppreference显示了脚注116中提到的虚拟调度示例(N3337,N4140中的脚注118):
struct D; struct B { virtual operator D() = 0; }; struct D : B { operator D() override { return D(); } }; int main() { D obj; D obj2 = obj; // does not call D::operator D() B& br = obj; D obj3 = br; // calls D::operator D() through virtual dispatch }