从方法链中使用的临时移出

2024-02-20

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

#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())
        ;
    }

error:无法绑定类型的右值引用Bar&&到类型的左值Bar

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

尝试重载 doThings 并不能解决问题:

error: Bar&& Bar::doThings() &&不能超载


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

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

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

    std::unique_ptr<int> m_content; // A non-copyable type
    };
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从方法链中使用的临时移出 的相关文章

随机推荐