简体   繁体   English

为什么使用此全局`operator <<`无法编译?

[英]Why does using this global `operator<<` fail to compile?

Here is the interface in a nutshell 简而言之,这是界面

#include <iostream>

struct Graph
{
    typedef int Parameter;

    struct Render
    {
        void to (std :: ostream &) {}
    };

    Render render (Parameter) {}
};

std :: ostream &
operator << (std :: ostream &, Graph :: Render &);

int main ()
{
    Graph () .render (0) .to (std :: cout);

    // std :: cout << Graph () .render (0);
}

The above will compile without complaint, unless you uncomment the last line. 除非您取消注释最后一行,否则上面的内容将毫无怨言地编译。

Why doesn't the global operator<< compile? 为什么全局operator<<编译?

You have overloaded your operator only for mutable lvalues, so the prvalue (the temporary value that is Graph().render(0) ) does not bind to it. 您仅对可变左值重载了运算符,因此prvalue(临时值Graph().render(0) )不会绑定到它。

You can either change your operator overload to use a const reference (which will accept lvalues and rvalues): 您可以将运算符重载更改为使用const引用(它将接受左值右值):

std::ostream & operator<<(std::ostream &, const Graph::Render &);
//                                        ^^^^^^^^^^^^^^^^^^^^^

Or you can add an additional rvalue overload: 或者,您可以添加其他右值重载:

std::ostream & operator<<(std::ostream &, Graph::Render &&);
//                                        ^^^^^^^^^^^^^^^^

If in doubt, go with the first solution. 如有疑问,请采用第一种解决方案。 It would be extremely surprising if printing a string representation of the object would require its mutation. 如果打印对象的字符串表示形式需要对其进行突变,那将非常令人惊讶。

(It is also kind of weird that Graph::render should return a new Render object by value, but that's your decision.) Graph::render应该按值返回一个新的Render对象也很奇怪,但这是您的决定。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM