usage of this pointer in std::bind - c++

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?

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.

Related

creating a std::bind to bind a class method within itself

I'd like to be able to bind a function with set parameters within itself - I've been given an implementation of scheduled callbacks wherein there's a multimap from std::chrono time signatures to std::function<void(void)>, and I want to have this method do some stuff and then schedule to call itself again in the future. Thus, creating a std::bind of itself to ultimately get into this multimap with an associated time.
I'm having a devil of a time actually trying to get the syntax right here, and I'm not really able to parse the error messages / see why things aren't working. For example,
#include <functional>
#include <iostream>
class x {
public:
void testBind(char y);
};
void x::testBind(char y) {
std::cout<<"Blah! " << y << "\n";
auto boundItself = std::bind(&x::testBind, &x, std::placeholders::_1);
boundItself('h');
}
produces the following error on the line with std::bind:
error C2275: 'x': expected an expression instead of a type
https://godbolt.org/z/rncfchvPb
As a toy example, I should be able to get recursive printouts of Blah etc., but the syntax around Bind aren't being cooperative.
https://en.cppreference.com/w/cpp/utility/functional/bind
From the std::bind documentation, here's an example that DOES work:
struct Foo {
void print_sum(int n1, int n2)
{
std::cout << n1+n2 << '\n';
}
int data = 10;
};
int main()
{
using namespace std::placeholders;
Foo foo;
auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
f3(5);
return 0;
}
Now, I notice that in this example, there's first &Foo:print_sum, e.g. capital F, e.g. the class definition, while the second argument is &foo, a lowercase, e.g. a specific instance of the class. But how do I get this argument into my bind definition? Do I need to declare a static global instance of my class to use as a sort of placeholder here?
You came close by noticing that the second parameter had to be a specific instance of the class. This is an application to std::bind of a more general principle – every call to a non-static member function must be associated with an object of the class. In std::bind, this principle takes the form of providing the object as the second parameter. In more common cases, this principle takes the form of providing an object in front of the function call, as in obj.testBind('h'), where obj had been earlier declared as x obj;.
So the question is which object should be associated with the bind? Since the context is inside a member function, one likely possibility is the object associated with that call. Remember, every call to testBind() must be associated with an x object. This applies to the call you hope to make in the future (via the bind) and to the call that is currently executing. Since the goal is to repeat the current call, it makes sense to use the current object.
The name given to the address of the current object is this, so the bind you are looking for is probably
std::bind(&x::testBind, this, std::placeholders::_1)
// ^^^^
Alternatively, you could abandon std::bind and use a lambda.
auto boundItself = [this](char yy) { testBind(yy); };
Wait a minute! Where is the object for the call to testBind() in the lambda version? What happened to the principle driving this answer? (If you were already asking that before reading this far, good observation skills.)
Nothing happened to the principle. We have simply stumbled into a different context. Inside a member function, there is a shorthand syntax that obscures the principle. Accessing members of the current object is so common that the compiler will assume the current object if none is specified. This assumption spills into lambdas that capture this. The statement testBind(yy); in the lambda is merely shorthand for this->testBind(yy);. There is still an object associated with the new call to testBind().

How to pass argument to std::bind to a function?

I have the following code which used std::bind :
EventListenerCustom* _createNewObjectlistener =
eventDispatcher->addCustomEventListener(Constants::MY_EVENT,
std::bind(&MyClass::MyFunction, this, std::placeholders::_1));
It seems I create many different kinds of object listeners, where the only difference is the event, and the function being called. If I wanted to encapsulate the above code into a function:
How would I pass MyClass::MyFunction as an argument to the function ?
What would the function signature and parameters look like ?
I imagine the function would look something like this:
EventListenerCustom* MyFunc(<What Goes Here> functionToBeBound,<What goes here> object,std::string EVENT){
EventListenerCustom* eventListener = eventDispatcher->addCustomEventListener(EVENT, std::bind(functionToBeBound, object, std::placeholders::_1));
return eventListener;
}
What should the function look like ? And How do I call it? What would the calling code look like?
EDIT: Concrete details:
I have many listener objects which are created in identical ways:
auto eventDispatcher = _dragNode->getEventDispatcher();
_createNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::MY_EVENT, std::bind(&MyClass::myOtherFunction, this, std::placeholders::_1));
_moveNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::MY_EVENT2 std::bind(&MyClass::myFunction, this, std::placeholders::_1));
Constants::MY_EVENT etc are just const char* .
The only difference is the Function being called, and the string constant used as an event name. How can I encapsulate this into a function ? I have tried John Zwinck's solution below, but for some reason I can't get it to compile because the compiler complains:
: No viable conversion from '__bind<void (*&)(cocos2d::EventCustom *), MyNameSpace::MyClass *, const std::__1::placeholders::__ph<1> &>' to 'const std::function<void (EventCustom *)>'
To make it simpler, create a typedef for a pointer to any member function in MyClass which has the appropriate signature:
typedef void (MyClass::*MyMemberFn)(int); // replace int and void as needed
Then:
EventListenerCustom* MyFunc(MyMemberFn functionToBeBound, MyClass* object, std::string EVENT){
return eventDispatcher->addCustomEventListener(EVENT, std::bind(functionToBeBound, object, std::placeholders::_1));
}
What you're really looking for is std::function. The documentation for such is here: https://en.cppreference.com/w/cpp/utility/functional/function
Their example is really good at explaining how it's used, but for your case (or related) try this:
std::function<void(int)> func1 = std::bind(MyClass::MyFunction, this, std::placeholders::_1));
What this will do is create an object which can be called, and the first argument is forwarded on to the first argument of the member function, both of which should be int type, and it returns nothing. You don't actually need address-of operator for the function name.
The cool part here is that the object returned by std::bind can be passed into the constructor of std::function and all its information is preserved. So when you need a concrete type that can be copied and all that cool stuff (passed into a function NOT by reference for example) then use a std::function as it will do the job, as long as it's not trying to copy a non-copyable type or something. std::function can also be initialized with a function pointer. It's generally just "better" than function pointers for C++, especially combined with std::bind to handle classes.
I could write out more examples, but check out the link above, and check out std::bind on that same website. Both should help.

Why is the "this" prefix required when invoking a member function via a function pointer?

AFAIK, in C++, invoking another member function within a member of function of the same class should not require the "this" prefix as it is implicit. However, in the specific case of using function pointers, the compiler requires it. The following code compiles correctly only if I include the "this" prefix for the call via func pointer -
When function pointers are used can the compiler deduce when it points a member func of the same class?
class FooBar
{
private:
int foo;
public:
FooBar()
{
foo = 100;
}
int GetDiff(int bar)
{
return abs(foo - bar);
}
typedef int(FooBar::*MyFuncPtr)(int);
void FooBar::Bar()
{
MyFuncPtr f = &FooBar::GetDiff;
(this->*f)(10);
GetDiff(10);
}
};
It's required, because member function pointers (which are not the same thing as function pointers) are not bound, and you can use them with different objects.
(this->*f)(10);
(foo.*f)(10);
// etc.
When you invoke an instances member function the this pointer is implicitely put to the function parameters. Thus you need to specify this also when invoking that function via a function pointer.
f isn't a member of the class, but a local variable, you could also specify another instance pointer instead of this, so the compiler can't deduce that. Same for member function pointers as class member variables.
The simple question is that it is a matter of language design and the language was designed this way.
Inside a member function, and to ease the common syntax when the compiler encounters an identifier it performs lookup starting from this class (plus ADL on the arguments), and if the lookup finds an unambiguous non-static member of this type (or of a base type) then the compiler will inject this-> for you (that is, applies operator-> to the this pointer).
In the case of a pointer to member the process is quite different. The pointer (which is not really a pointer, but for the sake of argument) is found by lookup, but it is your responsibility to provide the object on which it will be called and use the appropriate operator (either .* for calling a pointer to member on a reference, or ->* for calling the member on a pointer).
Note that the operators that are called are different, and that the process is different altogether (in one case lookup finds a member, in the other it finds a variable that happens to be pointer-to-member), but the most important part is that calling pointers to members is infrequent enough, and calling them on this is even less frequent that it does not not to warrant an exemption on the syntax for a small use case.
f isn't a member of FooBar. So if you want to call f on an instance of FooBar, you have to tell it which instance.
In your example, f does contain a member of FooBar, but the compiler doesn't know that.
This happens because of the way the C++ runtime handles classes while you are not looking.
Basically it would be inefficient to store the function pointers in the instance, so the compiler builds a class specific table with function pointers that have the same arity as the member functions you defined and that get the this pointer passed at runtime (AFAIK visualc passes the pointer via ecx, I'm not entirely sure what happens on GCC)
So basically when you do
instance->foo(10);
You are telling the runtime to call function foo with the parameter 10 and pass (instance) as the this pointer, wich is why you have to specifically say which object it has to be called on.

Store pointers to memberfunctions of different classes

I am trying to store pointers to memberfunctions of different Classes in C++. What are the possibilities in C++?
I would like to do this:
class A {
T0 f(T1,T2);
};
class B {
T0 g(T1,T2);
T0 h(T1,T2); //interfaces cant be used since the number of functions per class differs.
};
typedef WHATTOPUTHERE type;
type x;
x = A::f;
x = B::h;
Update: Another Problem is that the code should be continueable like this:
B myB;
myB::x(a,b); //not sure about the syntax, should result in myB::h(a,b) being called
This means that I can not bind at the time I store the pointer, since the instance does not exist (yet).
Function objects to encapsulate your function pointers should work.
boost::function is one option, maybe something like this:
class SomeObj
{
public:
void SetInt(int i);
};
SomeObj myObject;
std::vector<boost::function> memberFuncs;
// in the template arg to boost::bind specify the function type
// _1 here denotes late binding so you can pass whatever value you want when invoked
// you could simply bind a parameter as a variable or literal instead
memberFuncs.push_back(boost::bind<void(int)>(&SomeObj::SetInt, &myObject, _1));
memberFuncs[0](42); // myObject->SetInt(42);
Untested/uncompiled code disclaimer this is just for a general idea.
One possible implementation (using C++11) can easily be done using std::function and a lambda like this:
typedef std::function<void(int)> FunctionType;
SomeClass someClass;
FunctionType func = [&someClass](int argument)
{
someClass.SomeMemberFunction(argument);
};
To have a pointer to Fred::f(char, float) you need this sort of pointer:
int (Fred::*)(char,float)
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
The answer to your particular question is that there is no type that you can add to the typedef and make the code compile. The reason is that member function pointers take a hidden argument of the type of the class form which they are obtained. The type of that hidden argument will be different when you take the address of a member function from A or B.
The next question is whether it makes sense or not from a design perspective, considering that you cannot apply the function pointer A::f to an instance of type B, what is the point of considering member pointers of A and B together?
Now, there are possible workarounds for this particular problem (if it makes sense in your case, but I would first review the design) that involve performing type-erasure on the function pointer to remove the hidden argument and generate an object that is callable with the given set of arguments and return type that is common to all of the member functions. This is already done inside std::function (alternatively boost::function if your compiler does not support C++11), as has been suggested before:
A a_instance;
std::function< T0 (T1,T2) > f( std::bind( &A::f, &a_instance, _1, _2 ) );
T0 r = f( T1(), T2() );
Note that part of the trick is that std::bind binds the member function pointer with the pointer to the instance, filling in the hidden argument, while leaving the other two arguments unbound. At this point, because the result of bind does no longer depend on the type of the first argument, type-erasure can be applied removing A from the type of the resulting object.

Using boost thread and a non-static class function

So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using "this" and boost::bind etc. It really doesn't make much sense to me and all the examples I could find had the boost::thread object launched within the same class as the function it was starting with so this could be used. I however, am launching the thread in a different class so I'm afraid by using "this", I will be saying the "this" is from the class I am creating the thread from, rather than the one the function is in (I'm probably wrong, I need to learn more about this "this" guy). Here is an example of my source I am having the problem with.
ANNGUI.h
class ANNGUI
{
private:
boost::thread *GUIThread;
Main *GUIMain;
public:
// Creates the entire GUI and all sub-parts.
int CreateGUI();
}
ANNGUI.cpp
int ANNGUI::CreateGUI()
{
GUIMain = new Main();
GUIThread = new boost::thread(GUIMain->MainThreadFunc);
};
This isn't all the source, but I think my problem is in here somewhere, I know I have to deal with the "this" somehow, but I'm unsure how. I Could use a static function, but I didn't really want to make my variables static either.
Thanks.
Also, Is there any very good resource for using any boost libraries? Their web site documentation seems good, but over my head.
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.
If you were to call bind from outside a class member function, you might say something like:
int main()
{
Foo f;
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}
Here, we're using Foo::some_function as our thread function. But we can't use this because we're calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:
void Foo::func1()
{
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}
If a member function is static, or is simply a regular (non-member) function, then you don't need an instance pointer at all. You would just do:
boost::thread* thr = new boost::thread(some_regular_function);
As others mentioned, when you want to call an object method in a new thread, you have to supply the address of that object. But you don't need to call boost::bind, you can use the overloaded boost::thread constructor like this:
GUIThread = new boost::thread(&Main::MainThreadFunc, GUIMain);
If the method is in the same class you use this to get the address of the current instance, e.g.:
t = new boost::thread(&myclass::compute, this);
If the method has parameters, you can specify them after the second argument, e.g.:
t = new boost::thread(&myclass::compute, this, p1, p2);
boost::bind is your friend (it can sometimes have a rough way of showing it though)!
use GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain));
and then make your MainThreadFunc a regular member. That means that you can use the instance variables directly like you would normally do.
Something like this:
class GUIMain {
public:
GUIMain() : m_Member(42) {}
void MainThreadFunc() {
// use all members as you would normally do
std::cout << m_Member << std::endl;
}
private:
int m_Member;
};
In cases like this it is useful to think of non-static member functions as free functions that take the this as first parameter, for example in your case void MainThreadFunc(Main* this).
boost::thread accepts a nullary functor, so you have to pass it a nullary functor which contains a reference to the instance GUIMain and calls GUIMain->MainThreadFunc which, seen as I explained above, would be something like MainThreadFunc(GUIMain).
Boost (and now also C++ with TR1) provides helpers to create such functors, namely boost::bind (or alternatively boost::lambda::bind). The expression boost::bind(f, arg1, arg2, ...) means "return a nullary functor which calls f(arg1, arg2, ...)".
That said, you can use the following expression to create the thread:
GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain))
If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:
#include <boost/thread.hpp>
struct th {
void operator()();
};
void th::operator()()
{
for (;;) {
// stuff
}
}
int main()
{
th t;
boost::thread my_thread( t ); // takes a copy of t !
my_thread.join(); // blocks
return 0;
}