Workarounds for no 'rvalue references to *this' feature

谁说我不能喝 提交于 2019-12-31 08:12:08

问题


I have a proxy container class around a movable object, and wish the proxy to be able to implicitly yield an rvalue reference to the underlying object, but only when the proxy itself is being moved.

I believe that I will be able to implement this behaviour as per proposal n2439 "Extending move semantics to *this", but it is not yet available in a release of gcc and won't be for a while.

The code below is what I am ultimately aiming for, but is not currently possible. Until this feature is available to me, are there any equivalent workarounds?

template< class T >
struct movable_proxy {
    operator T&&() && {
        return std::move(value);
    }

    operator const T&() const& {
        return value;
    }

private:
    T value;
};

回答1:


Good question. I attempted writing a similar sort of proxy class recently but never achieved a good solution. The best I found was calling a member function on every use where the proxy was required to be an r-value:

ORef<T> move() {
    return ORef<T>( this->release() );
}

This changes the semantics of declaring something an r-value from std::move(proxy) to proxy.move(), but also allows the possibility of returning an object of a different type (implicitly convertible to your required type).

My coding practice using this was to always pass proxy objects as rvalues which forced manual specification of semantics (move, shared reference, copy or whatever), but that of course makes usage errors a potential problem (e.g. calling x.move() prior to the final usage of x).



来源:https://stackoverflow.com/questions/14562984/workarounds-for-no-rvalue-references-to-this-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!