C++ 为什么istream不支持右值提取

C++ 为什么istream不支持右值提取,c++,c++14,rvalue,C++,C++14,Rvalue,我有一个类,它围绕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 << "]";

我有一个类,它围绕
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;
  }
};
我可能会构建它,但因为我没有看到任何
>&&
的东西,所以感觉不对劲


>&&&
在某种程度上是禁止的还是邪恶的?

右值引用只能绑定到右值。大多数情况下,这正是您想要的——它确保(例如)在编写move-ctor/assignment操作符时,不会意外地在左值上调用它,并破坏仍将要使用的内容

我不确定在这种情况下为什么要使用右值引用,但您确实需要这样做是有原因的,当它是模板参数时,您至少可以使用相同的语法:

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;
}
struct Wrap
{
std::string s;//输出需要常量ref,输入需要非常量
friend std::ostream&operator>w;
}
不确定这是否真的有用。

(在gcc版本7.3.0(Ubuntu 7.3.0-16ubuntu3)上测试)

您的代码按原样运行(在此处运行:):

#包括
#包括
结构包裹{
std::string&s;//输出需要常量ref,输入需要非常量
friend std::奥斯特雷姆和运营商w.s;
回报是;
}
};
int main(){
std::string a=“abcd”;
std::cin>>包裹{a};

std::cout Unrelated,
os>.
-很确定你的意思是
os你需要提供一个为什么你会通过电话发布非常技术性的问题?这是使用什么工具链?我问,因为,除非我没有看到眼前的东西,@Michał是的,我是打勾的人。FWIW你也可以用
包装
操作符>>
中按值创建对象(在写案例中为
操作符)。我传递Wrap一个成本字符串&…使事情变得不同
my_istream >> Wrap{some_string}; // doesn't compile - cannot bind lvalue to rvalue
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;
}
#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};
}