Boost.Ref 库在头文件 boost/ref.hpp 中提供了两个函数,boost::ref() 和 boost::cref()。例如,如果您将 std::bind() 用于需要引用参数的函数,它们将很有用。因为 std::bind() 按值获取参数,所以您必须显式处理引用。
Boost.Ref 在 C++11 中被添加到标准库中,您可以在其中找到头文件中的函数 std::ref() 和 std::cref() 功能。
示例 42.1。使用 boost::ref()
- #include <boost/ref.hpp>
- #include <vector>
- #include <algorithm>
- #include <functional>
- #include <iostream>
-
- void print(std::ostream &os, int i)
- {
- os << i << std::endl;
- }
-
- int main()
- {
- std::vector<int> v{1, 3, 2};
- std::for_each(v.begin(), v.end(),
- std::bind(print, boost::ref(std::cout), std::placeholders::_1));
- }
运算结果:

在示例 42.1 中,函数 print() 被传递给 std::for_each() 以将 v 中的数字写入输出流。因为 print()