std::ref, std::cref
来自 zh.cppreference.net
| 定义于头文件 <functional>
|
||
template< class T >
std::reference_wrapper<T> ref( T& t ) noexcept;
|
(1) | (C++11 起) (C++20 起 constexpr) |
template< class T >
std::reference_wrapper<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>
cref( std::reference_wrapper<T> t ) noexcept;
|
(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; // 递增函数对象中存储的 n1 副本 ++n2; // 递增 main() 中的 n2 // ++n3; // 编译错误 } 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
引用包装器
(类模板) |