Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of this pointer in std::bind

Tags:

c++

c++11

I was trying to read and understand std::bind when I stumbled on below answer:

Usage of std::bind

I see one statement like below:

auto callback = std::bind(&MyClass::afterCompleteCallback, this, std::placeholders::_1);

I am unable to understand what is the usage of 'this' pointer and when one should make use of it? 'this' pointer means the current object address itself so it would something mean that 'use this object' - if so how can I use the same statement outside the class still having the same meaning?

like image 822
Programmer Avatar asked Nov 28 '17 13:11

Programmer


People also ask

What does std :: bind do in C++?

std::bind is for partial function application. That is, suppose you have a function object f which takes 3 arguments: f(a,b,c); You want a new function object which only takes two arguments, defined as: g(a,b) := f(a, 4, b);

Why is std :: bind used?

std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.

What is boost :: bind?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.


1 Answers

Inside the class, outside the class, that's not really important to the use of std::bind. A non-static member function must be called with a valid object of the class it is a member of. std::bind considers that object to be the first argument it is given after the callable, plain and simple.

So you can do it as you noted, inside the class, and supply the "current" object as the first bound argument.

Or you can do it outside the class, if the member is accessible, and supply some object (as @Scheff pointed out):

MyClass myClass; 
using namespace std::placeholders;
auto callback = std::bind(&MyClass::afterCompleteCallback, &myClass, _1);

You may even choose not to bind the object at all, and leave a placeholder for that as well:

MyClass myClass; 
using namespace std::placeholders;
auto callback = std::bind(&MyClass::afterCompleteCallback, _1, _2);

callback(myClass, /*Other arg*/);

Also, and despite the fact you tagged c++11. With the changes to lambdas in c++14, there really is no reason to use std::bind anymore.

like image 197
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 00:11

StoryTeller - Unslander Monica