I recently studied link forwarding to C ++, and below is a summary of my current understanding of the concept.
Let's say I have a template function foothat translates a forwarding link to a single type argument T.
template<typename T>
void foo(T&& arg);
If I call this function with lvalue, then it Twill be output as T&if the parameter is of argtype T&due to the rules for dropping the link T& && -> T&.
If this function is called with an unnamed temporary, for example, the result of a function call, then it Twill be displayed as Tif the parameter is of argtype T&&.
Inside, foohowever arg, it is a named parameter, so I will need to use std::forwardit if I want to pass the parameter along with other functions and still maintain its category of values.
template<typename T>
void foo(T&& arg)
{
bar(std::forward<T>(arg));
}
As far as I understand, cv qualifiers are not subject to this forwarding. This means that if I call foo with a named constant variable, it Twill be inferred as const T&, and therefore the type argwill also be const T&due to the rules for dropping the link. For const rvalues Twill be output as const Tand therefore argwill have a type const T&&.
It also means that if I change the value arginternally foo, I will get a compile-time error if I did infact by passing it a constant variable.
.
, .
template<typename T>
class Container
{
public:
void insert(T&& obj) { storage[size++] = std::forward<T>(obj); }
private:
T *storage;
std::size_t size;
};
- insert obj, std::forward, T, insert infact .
, , -, const lvalue:
void insert(const T& obj).
, ( ) , insert .
, .
- ? const lvalue, .
void insert(const T& obj);
void insert(T&& obj);
, std::vector , push_back .
void push_back (const value_type& val);
void push_back (value_type&& val);
( const value_type&)?