Why is std::remove_reference used in std::move?

lin*_*fil 6 c++ syntax reference move-semantics

I tried implementing std::move, which uses std::remove_reference, however it seems to work without it. Please, give me an example in which my implementation will fails whithout std::remove_reference.

template <class type> type && move(type & source) { return (type &&) source; }
template <class type> type && move(type && source) { return (type &&) source; }
Run Code Online (Sandbox Code Playgroud)

Is std::remove_reference used only to avoid overloading std::move?

Here is a test class to help you:

class test {
public :
    test() { }
    test(const test & source) { std::cout << "copy.\n"; }
    test(test && source) { std::cout << "move.\n"; }
};
Run Code Online (Sandbox Code Playgroud)

Not a duplicate of How does std::move() transfer values into RValues? because my question includes an example that seems to show that std::remove_reference is useless in this case + the sub-question.

Waq*_*med 2

我尝试实现 std::move,它使用 std::remove_reference,但似乎没有它也能工作。

是的,它正在工作,因为您显式提供了左值引用的重载。Whilestd::remove_reference仅在您使用转发引用时才相关。

如果你去掉这一行: Godbolt

template <class type> type && move(type & source) { return (type &&) source; }
Run Code Online (Sandbox Code Playgroud)

并将您的函数称为:

test t2 = move(t1); //prints copy
Run Code Online (Sandbox Code Playgroud)

为了使这项工作正常进行,您必须使用std::remove_reference. 尝试一下 Godbolt

template <class type>
std::remove_reference_t<type> && move(type && source)
{
    return
    static_cast<std::remove_reference_t<type>&& >(source);
}

Run Code Online (Sandbox Code Playgroud)