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.
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
.