Function Binding and Partial Application

Binding Member Variables

Can std::bind be used to bind member variables in addition to member functions?

Abstract art representing computer programming

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.

This Question is from the Lesson:

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.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved