Binding Member Variables
Can std::bind be used to bind member variables in addition to member functions?
Yes, std::bind can be used to bind member variables as well as member functions. When binding a member variable, you need to provide a pointer to the member variable using the & operator.
For example, consider a simple Player struct with a std::string Name member variable:
#include <functional>
#include <iostream>
struct Player {
std::string Name{"Ariel"};
};
int main() {
Player PlayerOne;
auto GetName{std::bind(
&Player::Name, &PlayerOne)};
std::cout << GetName();
}ArielIn this example, we bind the Name member variable of PlayerOne using std::bind. The resulting GetName functor, when called, returns the value of PlayerOne.Name.
One thing to note is that when binding member variables, the functor returns a reference to the member variable. If you want to modify the member variable through the functor, you can do so directly:
#include <functional>
#include <iostream>
struct Player {
std::string Name{"Ariel"};
};
int main() {
Player PlayerOne;
auto GetName{std::bind(
&Player::Name, &PlayerOne)};
GetName() = "Anna";
std::cout << PlayerOne.Name << '\n';
}AnnaBinding member variables can be useful in scenarios where you want to provide access to specific member variables of an object without exposing the entire object.
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.