std::ref, std::cref
来自 cppreference.cn
定义于头文件 <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 引用包装器 (类模板) |