用户定义的对右值引用的转换无效 什么是推理,大多数版本的GCC,除了4.9-4.4.4和91.0,都认为C++ 11代码不正确,除非同时使用代码>学究< > -f/选项。 clang编译了它 struct A { int a; operator int() && { return a; } operator int&() & { return a; } }; void b(int &&) {} int main() { b(A{}); }
输出类似于:用户定义的对右值引用的转换无效 什么是推理,大多数版本的GCC,除了4.9-4.4.4和91.0,都认为C++ 11代码不正确,除非同时使用代码>学究< > -f/选项。 clang编译了它 struct A { int a; operator int() && { return a; } operator int&() & { return a; } }; void b(int &&) {} int main() { b(A{}); },c++,c++11,gcc,C++,C++11,Gcc,输出类似于: prog.cc: In function 'int main()': prog.cc:11:10: error: invalid user-defined conversion from 'A' to 'int&&' [-fpermissive] b(A{}); ^ prog.cc:4:5: note: candidate is: A::operator int&() & <near match>
prog.cc: In function 'int main()':
prog.cc:11:10: error: invalid user-defined conversion from 'A' to 'int&&' [-fpermissive]
b(A{});
^
prog.cc:4:5: note: candidate is: A::operator int&() & <near match>
operator int&() & { return a;
prog.cc:在函数“int main()”中:
程序cc:11:10:错误:从“A”到“int&&”[-fppermissive]的用户定义转换无效
b(A{});
^
prog.cc:4:5:注意:候选项是:A::运算符int&(()&)
运算符int&()&{返回a;
根据StoryTeller的评论,该问题显然与实现中的中间错误有关,并已修复,可能的解决方案可能是:
#include <utility> //std::move
#include <iostream>
struct A {
int a;
operator int const& () const { std::cout <<__PRETTY_FUNCTION__<<std::endl; return a; }
operator int&&() && { std::cout <<__PRETTY_FUNCTION__<<std::endl; return std::move(a); }
};
void b(int &&) {}
void b(const int &) {}
int main()
{
b(A{});
b(std::move(A{}));
A a;
b(a);
}
尝试
操作符int&&(){return std::move(a);}
。我假设操作符int()&&
返回int
,而不是int&
,gcc正确地确定,它不能从两个近似重载(int&
和int
)中进行选择,当尝试匹配int&
时。若我不得不猜测,我会说它和@RadosławCybulski有关,在这种情况下,运算符的选择取决于函数原型,而不是表达式的类型。当然,这是可行的
A::operator int&&() &&
A::operator int&&() &&
A::operator const int&() const