<functional>是函数对象库的一部分,并提供标准的哈希函数。
详见cppreference
std::reference_wrapper (c++11)
template< class T >
class reference_wrapper;
std :: reference_wrapper是一个类模板,它将引用包装在可复制的可分配对象中。它通常用作一种将引用存储在标准容器(例如std :: vector)中的机制,这些容器通常无法保存引用。
具体来说,std :: reference_wrapper是一个CopyConstructible和CopyAssignable包装器,它围绕对对象的引用或对T类型函数的引用。std :: reference_wrapper的实例是对象(可以复制或存储在容器中),但其实它被隐式转换为T& ,以便将它们用作通过引用基础类型的函数的参数。
如果存储的引用是Callable,则可以使用相同的参数调用std::reference_wrapper。
辅助函数std ::ref和std :: cref通常用于生成std::reference_wrapper对象。
std :: reference_wrapper也用于通过引用std :: bind,std :: thread的构造函数或辅助函数std :: make_pair和std :: make_tuple传递对象。
示例
#include <algorithm>
#include <list>
#include <vector>
#include <iostream>
#include <numeric>
#include <random>
#include <functional>
int main()
{
std::list<int> l(10);
std::iota(l.begin(), l.end(), -4);
std::vector<std::reference_wrapper<int>> v(l.begin(), l.end());
// can't use shuffle on a list (requires random access), but can use it on a vector

本文介绍了C++的<functional>库中的std::reference_wrapper,它允许在不可复制的容器中存储引用。同时讲解了std::bind,用于创建可调用对象,预先绑定部分参数。文中通过示例展示了这两个工具的用法。
最低0.47元/天 解锁文章
836

被折叠的 条评论
为什么被折叠?



