【问题标题】:invalid user-defined conversion to rvalue reference无效的用户定义转换为右值引用
【发布时间】:2019-12-19 16:41:44
【问题描述】:

除了 4.9.0-4.9.4 和 9.1.0 之外,大多数版本 gcc 都认为此 C++11 代码格式错误,除非同时使用 -pedantic-fpermissive 选项,这背后的原因是什么时间? clang 编译它。

struct A {
    int a;
    operator int() &&  { return a; }
    operator int&() &  { return a; }
};

void b(int &&) {}

int main()
{
    b(A{});
}

输出类似于:

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; 

【问题讨论】:

  • 试试operator int &amp;&amp; () { return std::move(a); }。我假设operator int() &amp;&amp; 返回int,而不是int &amp;&amp;,并且gcc 正确确定,当尝试匹配int&amp;&amp; 时,它不能从两个近重载(int&amp;int)中进行选择。
  • 如果我不得不猜测我会说它与这个gcc.gnu.org/bugzilla/show_bug.cgi?id=86521有关
  • @RadosławCybulski 在这种情况下,运算符的选择由函数原型决定,而不是由表达式的类型决定。当然可以了

标签: c++ c++11 gcc


【解决方案1】:

根据 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);
}

输出:

A::operator int&&() &&
A::operator int&&() &&
A::operator const int&() const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多