std::forward
cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (1) | ||
template< class T > T&& forward( typename std::remove_reference<T>::type& t ) noexcept; |
( C++11) ( C++14) |
|
template< class T > constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept; |
( C++14) | |
| (2) | ||
template< class T > T&& forward( typename std::remove_reference<T>::type&& t ) noexcept; |
( C++11) ( C++14) |
|
template< class T > constexpr T&& forward( std::remove_reference_t<T>&& t ) noexcept; |
( C++14) | |
1) , , T
, , , , :
template<class T>
void wrapper(T&& arg)
{
// arg
// , T
foo(std::forward<T>(arg));
}
-
wrapper()std::string,Tstd::string(std::string&,const std::string&std::string&&),std::forward,foo. -
wrapper()std::string,Tconst std::string&,std::forward,foo. -
wrapper()std::string,Tstd::string&,std::forward,foo.
2) .
(, ), , .
, , - :
// -
template<class T>
void wrapper(T&& arg)
{
foo(forward<decltype(forward<T>(arg).get())>(forward<T>(arg).get()));
}
struct Arg
{
int i = 1;
int get() && { return i; } //
int& get() & { return i; } //
};
, , (2) T, .
| t | , |
static_cast<T&&>(t)
() T. .
#include <iostream>
#include <memory>
#include <utility>
struct A
{
A(int&& n) { std::cout << " rvalue, n=" << n << '\n'; }
A(int& n) { std::cout << " lvalue, n=" << n << '\n'; }
};
class B {
public:
template<class T1, class T2, class T3>
B(T1&& t1, T2&& t2, T3&& t3) :
a1_{std::forward<T1>(t1)},
a2_{std::forward<T2>(t2)},
a3_{std::forward<T3>(t3)}
{
}
private:
A a1_, a2_, a3_;
};
template<class T, class U>
std::unique_ptr<T> make_unique1(U&& u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
template<class T, class... U>
std::unique_ptr<T> make_unique2(U&&... u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)...));
}
auto make_B(auto&&... args) // C++20
{
return B( std::forward<decltype(args)>(args)... );
}
int main()
{
auto p1 = make_unique1<A>(2); // rvalue
int i = 1;
auto p2 = make_unique1<A>(i); // lvalue
std::cout << "B\n";
auto t = make_unique2<B>(2, i, 3);
std::cout << "make_B\n";
[[maybe_unused]] B b = make_B(4, i, 5);
}
:
rvalue, n=2
lvalue, n=1
B
rvalue, n=2
lvalue, n=1
rvalue, n=3
make_B
rvalue, n=4
lvalue, n=1
rvalue, n=5
(C++11) |
rvalue ( ) |
(C++11) |
rvalue, ( ) |