用ref限定符实现方法

用ref限定符实现方法

本文介绍了用ref限定符实现方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我难以实现以下代码

template <class T>
struct Foo
{
    std::vector<T> vec;

    std::vector<T> getVector() && {
        // fill vector if empty
        // and some other work
        return std::move(vec);
    }

    std::vector<T> getVectorAndMore() &&
    {
        // do some more work
        //return getVector(); // not compile
        return std::move(*this).getVector(); // seems wrong to me
    }
};

int main()
{
    Foo<int> foo;

    auto vec = std::move(foo).getVectorAndMore();
}

问题是我无法调用 getVector 位于 getVectorAndMore 内,因为 this 不是右值。为了使代码编译,我不得不将 this 强制转换为右值。

The problem is that I can't call getVector inside getVectorAndMore because this is not rvalue. To make the code compile, I had to cast this to rvalue.

实现这种代码的任何好方法?

Is any good way to implement such code?

带有 return getVector();

错误消息是

main.cpp:17:16: error: cannot initialize object parameter of type 'Foo<int>' with an expression of type 'Foo<int>'
        return getVector(); // not compile
               ^~~~~~~~~
main.cpp:26:31: note: in instantiation of member function 'Foo<int>::getVectorAndMore' requested here
    auto vec = std::move(foo).getVectorAndMore();
                              ^
1 error generated.

推荐答案

return getVector(); // not compile

这等效于此:

return this->getVector(); // not compile

,因为 this 是左值,而不是右值, getVector()只能在rvalue上调用,因此会出错。

which wouldn't compile, because this is an lvalue, not an rvalue and getVector() can be invoked only on rvalue, hence the error.

请注意,总是 一个左值—甚至在rvalue-ref成员函数内部!

Note that this is always an lvalue — even inside rvalue-ref member function!

return std::move(*this).getVector();

这是调用 getVector()

这篇关于用ref限定符实现方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:41