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();
}
Ariel
In 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';
}
Anna
Binding 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.
Answers to questions are automatically generated and may not have been reviewed.
This lesson covers function binding and partial application using std::bind()
, std::bind_front()
, std::bind_back()
and std::placeholders
.