Binding and std::ref / std::cref
How can std::ref and std::cref be used with std::bind?
std::ref and std::cref are utility functions provided by the <functional> header that enable passing references to objects when using std::bind. These functions are particularly useful to avoid copying objects when binding them to a function.
Here's an example demonstrating how to use std::ref with std::bind:
#include <functional>
#include <iostream>
void SetValue(int& value, int newValue) {
value = newValue; }
int main() {
int value = 10;
auto SetValue10 = std::bind(
SetValue, std::ref(value), 10);
auto SetValue20 = std::bind(
SetValue, std::ref(value), 20);
SetValue10();
std::cout << "Value after SetValue10: "
<< value << '\n';
SetValue20();
std::cout << "Value after SetValue20: "
<< value << '\n';
}Value after SetValue10: 10
Value after SetValue20: 20In this example:
- The
SetValuefunction takes a reference to anintand a new value, updating theintwith the new value. - We create two bound function objects,
SetValue10andSetValue20, usingstd::bind. Here,std::ref(value)ensures thatSetValuereceives a reference tovaluerather than a copy. - When
SetValue10andSetValue20are called, they modify the originalvaluevariable.
Similarly, std::cref can be used to bind a const reference to an object, which is useful when you want to bind a reference to a const object or a temporary object that should not be modified.
Here's an example demonstrating std::cref:
#include <functional>
#include <iostream>
#include <string>
void PrintString(const std::string& str) {
std::cout << str << '\n'; }
int main() {
std::string tempStr = "Hello";
auto Print = std::bind(
PrintString, std::cref(tempStr));
Print();
}HelloIn this example:
- The
PrintStringfunction takes a const reference to astd::stringand prints it. - We create a temporary
std::stringobjecttempStrwith the value"Hello". - We use
std::cref(tempStr)to bind a const reference totempStr. - The
Printfunctor, when called, passes this const reference toPrintString, which prints the string.
By using std::cref, we ensure that the std::string object is not copied and is passed as a const reference to the bound function.
In summary, std::ref and std::cref are valuable tools for binding references to functions with std::bind, allowing you to avoid unnecessary object copying and maintain the integrity of the original objects.
Function Binding and Partial Application
This lesson covers function binding and partial application using std::bind(), std::bind_front(), std::bind_back() and std::placeholders.