用户定义的到右值引用的转换无效
invalid user-defined conversion to rvalue reference
除了4.9.0-4.9.4 和 9.1.0 之外,大多数版本 gcc 都认为这个 C++11 代码格式不正确,除非同时使用-pedantic
和-fpermissive
选项,这背后的原因是什么? 叮当编译了它。
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;
根据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
相关文章:
- 强制转换为引用类型
- 如何将 int 引用安全地转换为长引用?
- 右值引用转换后的地址更改
- C++将引用转换为指针?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 将常量引用转换为智能指针而不复制
- 为什么不能将继承自(非模板)类 B 的实例化类模板 A 的引用转换为对 B 的引用?
- 通过 see 命令引用转换运算符
- 将项目转换为 qt5 并将未定义的引用转换为 'vtable for qt5 和 cmake
- 从 r 值引用转换为 l 值引用,为什么有效
- C++从右值引用转换为右值引用 a unique_ptr
- 将引用转换为 C++ 中的指针表示形式
- 如何正确地将引用转换为指针
- 正在将常量结构引用转换为非常量指针
- 将传递引用转换为传递返回
- 将.net引用转换为c++引用
- c++向量引用转换
- 如何将对int8_t的引用转换为对uint8_t的引用
- 如何在c++中将数字字符引用转换为Unicode
- 是否可以将对 std::list<int*> 的引用转换为对 std::list<const int*> 的引用?