为什么istream不支持右值提取
Why doesnt istream support rvalue extraction
我有一个类,它封装在std::string
周围以提供格式:
struct Wrap {
std::string& s; // need const ref for output, non const for input
friend std::ostream& operator<< (std::ostream& os, const Wrap& w) {
os << "[" << w.s << "]";
return os;
}
friend std::istream& operator>> (std::istream& is, Wrap&& w) {
Is >> ......;
return is;
}
};
输出也可以:
my_ostream << Wrap{some_string};
因为将temp Wrap绑定到const ref是可以的。
但输入不太好:
my_istream >> Wrap{some_string}; // doesn't compile - cannot bind lvalue to rvalue
我可能构建了它,但由于我没有看到任何>> &&
,所以感觉有些不对劲。
>>&&
在某种程度上是被禁止的还是邪恶的?
(在gcc 7.3.0版本(Ubuntu 7.3.0-16ubuntu3(上测试(
您的代码可以按原样运行(在此处运行:http://cpp.sh/9tk5k):
#include <string>
#include <iostream>
struct Wrap {
std::string& s; // need const ref for output, non const for input
friend std::ostream& operator<< (std::ostream& os, const Wrap& w) {
os << "[" << w.s << "]";
return os;
}
friend std::istream& operator>> (std::istream& is, Wrap&& w) {
is >> w.s;
return is;
}
};
int main() {
std::string a = "abcd";
std::cin >> Wrap{a};
std::cout << Wrap{a};
}
您应该能够将Wrap作为r值传递。如果你是在线创建的,这正是发生的事情。
将r值与const-ref绑定也应该(而且确实(起作用。
右值引用只能绑定到右值。大多数情况下,这就是你想要的——它确保(例如(当你编写一个移动ctor/赋值运算符时,你不会意外地在左值上调用它,并破坏仍将使用的东西。
我不知道你为什么要在这种情况下使用右值引用,但你确实需要它是有原因的,当它是模板参数时,你至少可以使用相同的语法:
struct Wrap
{
std::string s; // need const ref for output, non const for input
friend std::ostream &operator<<(std::ostream &os, const Wrap &w)
{
os << "[" << w.s << "]";
return os;
}
template <class T>
friend std::istream &operator>>(std::istream &is, T &&w)
{
is >> w.s;
return is;
}
};
int main() {
int x;
Wrap w;
std::cin >> w;
}
但不确定这是否真的有用。
相关文章:
- 为什么istream不支持右值提取
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- Casablanca/cpprestsdk listener.support接受函数,但不支持方法
- 为什么C++不支持对未初始化变量进行智能分析?
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 在 Ubuntu 18.04 上编译 GLSL 着色器时"不支持 GLSL 3.30"?
- 为什么联机C++ IDE 不支持"graphics.h"头文件?
- Clang编译器不支持aarch64-apple-darwin上的-fxray-instrument
- 为什么我的 clang 格式不支持 PPDirectiveIndentStyle 选项?
- 为什么某些 STL 容器(堆栈、队列、优先级队列)不支持迭代器?
- 为什么不支持 Xcode 1.5?
- C++20 从括号中的值列表初始化聚合,不支持内部数组
- 为什么结构化绑定不支持可变数组?
- 您选择的 CPU 不支持 x86-64 指令集
- 将数据发送到多个客户端 UDP 时不支持地址族
- 缺少类型说明符 - 假定为 int.注意 c++ 不支持 default-int
- 瓦尔格林德"不支持arch_prctl选项"
- 错误:C4430:缺少类型说明符-假定为int.注意:C++不支持default-int
- 不支持 GLSL 330 内核
- 防止为字符串流提取运算符不支持的类型实例化模板类 (>>)