How do you call a function in a function using std::? - c++

std::vector<char>function(std::string word) {
}
namespace::json getList(){
function();
}
I was just wondering if im suppose to call the function on top by including std::function(argument)

No, you don't need nor should you use the std::function class to call function. The std::function class is more like a function pointer wrapper. It lets you work with functions as data more easily.
For example, std::function<T> func represents some parameterless function that returns an object of type T.
Refer to the documentation for std::function for more information.

Related

function pointer is not a function or function pointer

I have following problem:
void MyClass::LoopFunction(vector<Item>& items,void (MyClass::*funcy)(vector<Item>&,int))
{
for(SInt32 i = 0; i < 50; i++)
{
funcy(items,i);
}
}
It says:
Called object type 'void(MyClass::*)(vector<Item>&,int)' is not a function or function pointer
Can anyone help me to find a solution for this?
funcy is a pointer to a member function, so you need to call it on an instance of the class, like this:
(this->*funcy)(items,i);
The thing with non-static member functions is that they have an invisible first argument which the compiler will turn into this inside the member function. This means that you can't call (non-static) member functions without having an object instance to call the member function on.
In your case, if you want to call it using the this objectinside LoopFunction you need to do e.g.
(this->*funcy)(items, i);
If you want to call it on another object instance, you need to pass that object to the function, and use that instead.
Or you could use e.g. std::function and std::bind instead of the member function pointer. Or use a template parameter similar to the way the standard library handles callbacks, and which allows you to pass any callable object to the function (still have to use std::bind if you want to use a non-static member function though).

c++ using method as parameters to functions

I don't understand why the following code compile and works:
template<typename Predicate>
void foo(Predicate p) {
}
bool g(int n) {
}
void user(int n) {
foo(g);
}
foo is supposed to get a function object that will run on a data structure but I made the method simpler, because what I don't understand is how can this works? A method isn't an object. The normal way to do it is to create a new class, override operator() and then send an instance of that class.
Well, in this case the Predicate parameter is substituted by a function pointer of type bool (*func) (int). Nothing wrong with that...
The Predicate template argument can be almost any type. So you can use it for function pointers and classes as well as the basic types.
If you use the function argument p as a function, then it can be anything that is callable, like a function pointer, an object whose class have an operator() member function, a pointer to a static member function, a std::bind object, a std::function object or a lambda expression.
It can't be a pointer to a member function though, because to call a pointer to a member function you need an instance to call it on. For this use std::bind.

Passing member function as parameter

So I have this function:
void EventDispatcher::Subscribe(string eventName, void (*callback)(void *))
{
....
}
I am trying to pass class member function as a callback parameter there.
typedef void (*method)(void*);
void EventTester::RunTests()
{
_dispatcher = new EventDispatcher();
Event eventOne("one");
_dispatcher->Register("one", eventOne);
method p = &onOne;
_dispatcher->Subscribe("one", p);
}
void EventTester::onOne(void *args)
{
std::cout<<"Event one\n";
}
obviously this doesn't compile because onOne is not static and a member function. Is there any way of making it work this way?
You could use boost in C++03 or std::bind and std::function in C++11:
typedef boost::function<void(void*)> func_type;
void EventDispatcher::Subscribe(const string& eventName, const func_type& func_)
{
if ( ! func_.empty() ) {
// you could call the function
func_(NULL);
}
}
//Register looks like in a member function of EventTester:
...
_dispatcher->Subscribe("one",boost::bind(&EventTester::onOne,this,_1));
...
I'm going off the assumption that you have the ability to modify the signature of Subscribe. If not, my answer may not apply.
As you already noted, your pointer-to-member (aka method) is not the same as a plain function pointer. To use a pointer-to-member, you have to supply the class instance to call the function on as part of the method execution.
You could modify Subscribe to explicitly take in a pointer-to-member, which would expect an additional argument (the class instance). You would need Subscribe to store both the function pointer, and a pointer to your object instance. This would then require that all callbacks be implemented as pointers-to-members.
The preferred way to solve this problem is to use bind (either std::bind or boost::bind).
You would need to change your Subscribe function to take in a std/boost::function object instead of an explicit function pointer. This would permit callers of the Subscribe method to pass in any callable object (See the examples in the documentation of std::function)
You can then use bind to connect your class instance to your method pointer. This will return a functor object which will do the work of holding both your pointer-to-member and a pointer to your class instance.
For an example of how to use bind, see this link

Use class member functions as callbacks?

I would need a member function to be passed into a third party external method:
box_self_intersection_d(mycallback);
The box_self_intersection_d is a third party external static method, and I cannot modify it. mycallback is a method I want to pass it into the box_self_intersection_d, it is a class function and is accessing some members in this class ( have full control for this class and the mycallback)
Is there anyway I can use class member functions as callbacks without declaring them as static functions?
Edit: the signature of mycallback is (const box &boxA, const box &boxB), where box is a special class from the third party provider.
And the signature for box_self_intersection_d is
void box_self_intersection_d(RandomAccessIterator begin,RandomAccessIterator end,Callback callback)
If the function box_self_intersection_d takes a functional as parameters, and mycallback is a method of a class MyClass, you can use boost::bind:
box_self_intersection_d( boost::bind( &MyClass::mycallback, myClassInstance ) );
where myClassInstance is the instance of the class MyClass.
If the callback accepts a void* for user-defined data, you can use a static wrapper function that casts the void* argument to the class type and calls your member function.
Example:
static void Foo::callback_method(void* data) {
static_cast<Foo*>(data)->mycallback();
}
void Foo::register_my_callback() {
box_self_intersection_d(&Foo::callback_method, this);
}
Most sane callback libraries allow you to pass this void* argument to the functions as a way to have user-defined data in it. If not, you'll need to resort to the dirty method:
static Foo* Foo::callback_object;
static void Foo::callback_method() {
callback_object->mycallback();
}
void Foo::register_my_callback() {
callback_object = this;
box_self_intersection_d(&Foo::callback_method);
}
In general, if you need to pass a function, there is just no other way: Either you have a data side-channel like the void*, which your library provider seems to have omitted (and is clearly a bug in the library), or you need to transport the this pointer via a global variable.
There are a couple of possible workarounds. You can have a look here: http://www.newty.de/fpt/callback.html#member
In short, you can either:
declare a static "wrapper method" and pass the instance of the class to it,
or else store a pointer to the object as a global variable.
Hope that helps,
You haven't provided the signature box_self_intersection_d()
in general, if the signature is
void box_self_intersection_d( void *cb );
or even
void box_self_intersection_d( void (*cb)(const box&, const box&) );
then you cannot pass it a pointer to a member function.
The reason is that sizeof(a_member_function) is different than
sizeof(a_function_pointer). If this is the case, I think you are forced to use thiton's solution, and create a static function.
Since it's CGAL, the callback is actually a template parameter.
Its only constraints are "Callback must be of the BinaryFunction concept".
That is, it can be anything that is "callable" with the proper parameters.
This includes any object with a void operator() (const box&, const box&) member function.
Implementing that function in your class and passing *this for the callback would probably be the simplest solution.
There is a horrible solution that I can conceive of that means copying/pushing 'this' and function code to the calling stack, (or some other caller-allocated segment that can be made writeable and executable), and passing the address of the function to the library. The called-back function could then find its own code address, extract 'this' using an offset/pointer arith. and call a member function. Should work for multiple threads.
I hereby claim this years 'Gruesome Hack' award for a solution that makes developers feel physically ill but might still actually work if a project manager is pointing a shotgun at your head.
Rgds,
Martin

Why callback functions needs to be static when declared in class

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?
#include <iostream>
using std::cout;
using std::endl;
class Test
{
public:
Test() {}
void my_func(void (*f)())
{
cout << "In My Function" << endl;
f(); //Invoke callback function
}
static void callback_func()
{cout << "In Callback function" << endl;}
};
int main()
{
Test Obj;
Obj.my_func(Obj.callback_func);
}
A member function is a function that need a class instance to be called on.
Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.
A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it.
Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).
Callbacks need to be static so that they don't have an implicit this parameter as the first argument in their function signature.
Non-static methods require a 'this' instance, and can only be called upon an object instance.
However, it is possible to use non-static callbacks, but they are syntactically much harder to write. See http://www.newty.de/fpt/callback.html#member for an explanation.
Marshal Cline gives you the complete answer here
. The whole section contains everything you need to know.
To summarize it can explain that you need a static member because the this pointer isn't needed (unlike normal member methods). But it also covers that using a static may not be enough for all compilers since C++ calling convention might be different between C and C++.
So the recommendation is to use an extern "C" non-member function.
It needs to be static so that the function signature matches. When a member function is called, a hidden parameter is included in the call (i.e. the "this" pointer). In static member functions the this pointer is not passed as a parameter.
If you use function pointers, the runtime environment can't pass a reference to an instance when calling the function. But you may use std::mem_fun<>, in to use functors and member methods.