std::ref, std::cref
提供: 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>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| ヘッダ <functional> で定義
|
||
| (1) | ||
template< class T > std::reference_wrapper<T> ref(T& t) noexcept; |
(C++11以上) (C++20未満) |
|
template< class T > constexpr std::reference_wrapper<T> ref(T& t) noexcept; |
(C++20以上) | |
| (2) | ||
template< class T > std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept; |
(C++11以上) (C++20未満) |
|
template< class T > constexpr std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept; |
(C++20以上) | |
template <class T> void ref(const T&&) = delete; |
(3) | (C++11以上) |
| (4) | ||
template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; |
(C++11以上) (C++20未満) |
|
template< class T > constexpr std::reference_wrapper<const T> cref( const T& t ) noexcept; |
(C++20以上) | |
| (5) | ||
template< class T > std::reference_wrapper<const T> cref(std::reference_wrapper<T> t) noexcept; |
(C++11以上) (C++20未満) |
|
template< class T > constexpr std::reference_wrapper<const T> cref(std::reference_wrapper<T> t) noexcept; |
(C++20以上) | |
template <class T> void cref(const T&&) = delete; |
(6) | (C++11以上) |
関数テンプレート ref および cref は、結果のテンプレート引数を決定するためにテンプレートの実引数推定を使用して std::reference_wrapper 型のオブジェクトを生成する、ヘルパー関数です。
|
|
(C++20以上) |
引数
| t | - | ラップされる必要のあるオブジェクトへの左辺値参照または std::reference_wrapper のインスタンス |
戻り値
1)
std::reference_wrapper<T>(t)2)
ref(t.get())4)
std::reference_wrapper<const T>(t)5)
cref(t.get())3,6) 右辺値参照ラッパーは削除されています。
例
Run this code
#include <functional>
#include <iostream>
void f(int& n1, int& n2, const int& n3)
{
std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
++n1; // increments the copy of n1 stored in the function object
++n2; // increments the main()'s n2
// ++n3; // compile error
}
int main()
{
int n1 = 1, n2 = 2, n3 = 3;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
n1 = 10;
n2 = 11;
n3 = 12;
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
出力:
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12
関連項目
(C++11) |
CopyConstructible かつ CopyAssignable な参照ラッパー (クラステンプレート) |