std::ref介绍
std::ref是C++11中引入的一个模板函数,用于返回一个对象的引用。它可以用于将对象包装成引用类型,以便在需要引用类型的场景下使用。
使用场景:
- 将对象传递给需要引用类型的函数;
- 在容器中存储对象时,需要使用引用类型;
- 使用STL算法时,需要使用引用类型。
使用案例
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
void print_value(int& value) {
std::cout << "Value: " << value << std::endl;
}
int main() {
int a = 10;
int b = 20;
int c = 30;
// 将对象包装成引用类型并传递给函数
print_value(std::ref(a));
print_value(std::ref(b));
print_value(std::ref(c));
// 使用STL算法
std::vector<int> nums = { 1, 2, 3, 4, 5 };
std::for_each(nums.begin(), nums.end(), std::ref(print_value));
return 0;
}
输出结果:
Value: 10
Value: 20
Value: 30
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5