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: 20
In this example:
- The
SetValue
function takes a reference to anint
and a new value, updating theint
with the new value. - We create two bound function objects,
SetValue10
andSetValue20
, usingstd::bind
. Here,std::ref(value)
ensures thatSetValue
receives a reference tovalue
rather than a copy. - When
SetValue10
andSetValue20
are called, they modify the originalvalue
variable.
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();
}
Hello
In this example:
- The
PrintString
function takes a const reference to astd::string
and prints it. - We create a temporary
std::string
objecttempStr
with the value"Hello"
. - We use
std::cref(tempStr)
to bind a const reference totempStr
. - The
Print
functor, 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
.