Binding and Const Member Functions

How does std::bind handle const member functions?

When binding member functions using std::bind, the constness of the member function is preserved. If you bind a const member function, the resulting functor will also be const-qualified.

Consider the following example:

#include <functional>
#include <iostream>

struct Player {
  std::string GetName() const { return Name; }  
  std::string Name{"Anna"};
};

int main() {
  const Player ConstPlayer;  

  auto GetConstName{std::bind(
    &Player::GetName, &ConstPlayer)};  

  std::cout << GetConstName();
}
Anna

In this example, GetName() is a const member function of the Player struct. We create a const instance of Player called ConstPlayer.

When we bind &Player::GetName to &ConstPlayer using std::bind, the resulting GetConstName functor is const-qualified. This means that it can be called on const instances of Player.

Whilst we can bind a non-const member function to a const object, we will get a compilation error if we attempt invoke the function:

#include <functional>
#include <iostream>

struct Player {
  void SetName(const std::string& NewName) {
    Name = NewName;
  }  
  std::string Name;
};

int main() {
  const Player ConstPlayer;

  auto SetConstName{std::bind(
    &Player::SetName, &ConstPlayer, "Aria")};

  SetConstName();
}
error: attempting to reference a deleted function

In this case, binding &Player::SetName to &ConstPlayer will result in a compilation error once we invoke the function, because SetName() is a non-const member function and cannot be called on a const object.

Therefore, when binding member functions, it's important to consider the constness of the member function and the object it is being bound to. std::bind ensures that the constness is preserved and enforced appropriately.

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 Member Variables
Can std::bind be used to bind member variables in addition to 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