Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use std::function<void(void)> to call a method

Tags:

c++

I am trying to use an method that takes

  std::function<void()> 

as an input. Unfortunately I have never used this data type before and I am having problems understanding it. All I need to do it say when it is called execute a method, for example:

   std::function<void()> doThing = object.isMethod();

Although this syntax is obviously not correct. Can someone please explain this to me?

like image 621
user3319320 Avatar asked Dec 05 '14 17:12

user3319320


People also ask

How do you call a STD function in C++?

The stored callable object is called the target of std::function . If a std::function contains no target, it is called empty. Invoking the target of an empty std::function results in std::bad_function_call exception being thrown.

Is STD function copyable?

Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

Is std :: function a function pointer?

No. One is a function pointer; the other is an object that serves as a wrapper around a function pointer. They pretty much represent the same thing, but std::function is far more powerful, allowing you to do make bindings and whatnot.

What can you do with a void * C++?

When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal." If a pointer's type is void* , the pointer can point to any variable that's not declared with the const or volatile keyword.


1 Answers

You could bind the object to the method

std::function<void()> doThing = std::bind(&type::isMethod, &object);

or use a lambda

std::function<void()> doThing = [&]{object.isMethod();};
like image 69
Mike Seymour Avatar answered Sep 21 '22 20:09

Mike Seymour