std::ref, std::cref
來自 cppreference.com
定義於標頭檔案 <functional> |
||
template< class T > std::reference_wrapper<T> ref( T& t ) noexcept; |
(1) | (C++11 起) (C++20 起為 constexpr) |
template< class T > ref( std::reference_wrapper<T> t ) noexcept; |
(2) | (C++11 起) (C++20 起為 constexpr) |
template< class T > void ref( const T&& ) = delete; |
(3) | (C++11 起) |
template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; |
(4) | (C++11 起) (C++20 起為 constexpr) |
template< class T > std::reference_wrapper<const T> |
(5) | (C++11 起) (C++20 起為 constexpr) |
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) t
4) std::reference_wrapper<const T>(t)
5) t
3,6) 右值引用包裝器被刪除。
[編輯] 示例
執行此程式碼
#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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3146 | C++11 | 解包過載有時導致錯誤 | 已始終有效 |
[編輯] 參閱
(C++11) |
CopyConstructible 和 CopyAssignable 引用包裝器 (類模板) |