Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用户定义的对右值引用的转换无效 什么是推理,大多数版本的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 - Fatal编程技术网

用户定义的对右值引用的转换无效 什么是推理,大多数版本的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