Quick Q: How can a class template store either reference or value?
Quick A: This happen by default.
Recently on SO:
How can a class template store either reference or value?
You already wrote it (minus the required template <typename T>). The deduction rules for a forwarding reference preserve value category as follows:
- If t is bound to an lvalue of type T2, then T = T2&.
- If t is bound to an rvalue of type T2, then T = T2.
It's those deduction rules that std::forward relies on to do its job. And why we need to pass the type to it as well.
The above means that you instantiate holder directly with T2 in the rvalue case. Giving you exactly what you want. A copy is made.
As a matter of fact, two copies are made. Once to create the constructor argument t, and the other copy is to initialize obj_m from it. But we can get rid of it with some clever use of type_traits:
template <class T> class holder { T obj_m; // should be a reference if possible... public: holder(std::add_rvalue_reference_t<T> t) :obj_m { std::forward<T>(t) } {} }; template<typename T> auto hold_this(T && t) { return holder<T>(std::forward<T>(t)); }See it live. We use add_rvalue_reference_t to make t be of the correct reference type in each case. And "simulate" the argument deduction which would make obj_m { std::forward<T>(t) } resolve to initializing obj_m from the correct reference type.
I say "simulate" because it's important to understand the constructor argument for holder cannot be a forwarding reference because the constructor itself is not templated.
By the way, since you tagged c++17, we can also add a deduction guide to your example. If we define it as follows (with the feedback from T.C. incorporated):
template <class T> class holder { T obj_m; // should be a reference if possible... public: holder(T&& t) :obj_m { std::forward<T>(t) } {} }; template<typename T> holder(T&&) -> holder<T>;Then this live example shows you can define variables as hold h1{t}; and hold h2{test()};, with the same deduced types as the function return values from before.