Is there a cast (or standard function) with the opposite effect to `std::move`

前端 未结 4 1485
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 14:02

First off, this question is not a duplicate of Function dual to std::move? or of Does the inverse of std::move exist?. I am not asking about a mechanism to

4条回答
  •  青春惊慌失措
    2021-01-18 14:58

    Leave perfect forwarding out of your forwarding function, and you have no_move:

    template constexpr T& no_move(T&& x) {return x;}
    

    Just be sure pretending you have an lvalue-reference instead of an rvalue reference is ok, as that circumvents the protection against binding of temporaries to non-const references and such.

    Any code using this function is with near-certainty defective-by-design.

    In your example use-case, the proper way would be changing the argument-type of f() to const& so no such adaptor is neccessary, and using const_cast to add to the cache of saved computations.
    Be sure not to change non-mutable members on an object declared const though.

提交回复
热议问题