#include #include class MyType { public: MyType() {} MyType(MyType&& other) { fprintf(stderr, "move ctor\n"); } MyType(const MyType& other) { fprintf(stderr, "copy ctor\n"); }; }; void Store(const MyType& type) { fprintf(stderr, "store (copy)\n"); } void Store(MyType&& type) { fprintf(stderr, "store (move)\n"); } template void ProcessAndStore(T&& var) { // Process // ... // The type of |var| could be an rvalue reference, which means we should pass // an rvalue to Store. However, it could also be an lvalue reference, which // means we should pass an lvalue. // Note that just doing Store(var); will always pass an lvalue and doing // Store(std::move(var)) will always pass an rvalue. Forward does the right // thing by casting to rvalue only if var is an rvalue reference. Store(std::forward(var)); } int main(int argc, char **argv) { MyType type; // In ProcessAndStore: T = MyType&, var = MyType& ProcessAndStore(type); // In ProcessAndStore: T = MyType, var = MyType&& ProcessAndStore(MyType()); }