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();
}
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.

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.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Binding and Const Member Functions
How does std::bind handle const member functions?
Binding and Function Templates
Can std::bind be used with function templates?
Binding and Lambda Expressions
Can std::bind be used with lambda expressions?
Binding and Function Composition
How can std::bind be used for function composition?
Binding and std::ref / std::cref
How can std::ref and std::cref be used with std::bind?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant