从方法链中使用的临时位置移动 [英] Move from temporary used in method chaining

查看:64
本文介绍了从方法链中使用的临时位置移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做类似的事情:

I am trying to do something similar to this:

#include <vector>
#include <memory>

struct Bar
    {
    Bar& doThings()
        {return *this;}

    std::unique_ptr<int> m_content; // A non-copyable type
    };

struct Foo
    {
    Foo& append(Bar&& obj)
        {
        objects.push_back(std::move(obj));
        return *this;
        }

    std::vector<Bar> objects;
    };

int test()
    {
    Foo test;
    test.append(std::move(Bar{}.doThings())) //Ok
    // Not ok
      .append(Bar{}.doThings())
        ;
    }

错误:无法将类型Bar&&的右值引用绑定到类型Bar

error: cannot bind rvalue reference of type Bar&& to lvalue of type Bar

是否可以在没有显式std :: move的情况下进行这项工作?

Is it possible to make this work without the explicit std::move?

尝试重载doThings无法解决问题:

Trying to overload doThings does not solve the problem:

错误: Bar&& Bar::doThings() &&不能重载

推荐答案

您可以添加doThings()的引用限定的重载:

You can add ref-qualified overloads of doThings():

struct Bar
    {
    Bar& doThings() &
        {return *this;}

    Bar&& doThings() &&
        {return std::move(*this);}

    std::unique_ptr<int> m_content; // A non-copyable type
    };

这篇关于从方法链中使用的临时位置移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆