How to call a function from a function pointer? [duplicate] - c++

This question already has answers here:
Function pointer as parameter
(3 answers)
Closed 6 months ago.
How can you call a function from only a pointer to the function? For example:
void print()
{
std::cout << "Hello World!" << std::endl;;
}
void run_func(void* func)
{
func(); // what im trying to do (doesnt actually work)
}
int main()
{
run_func(print);
}
Expected output:
Hello World!
It's a bit like how std::thread creates a thread from the pointer of a variable.

Function pointers in function parameter lists need to be wrapped in parentheses. Change the one line, either by wrapping with parentheses or using the typedef'ed function parameter, and your sample works.
// Simplifies arcane function parameter synax.
typedef void (*FUNC_TO_RUN)();
void print()
{
std::cout << "Hello World!" << std::endl;;
}
// Change your parameter as follows. You need to wrap function
// pointers in parantheses.Or, use a typedef.
// void run_func(void *func())
// void run_func(void (*func)()) // Works, but harder to read
void run_func(FUNC_TO_RUN func) // Works, easier to read
{
func(); // what im trying to do (and now works)
}
int main()
{
run_func(print);
}

You have to change your parameter type of run_func to void (*func) (), which means func is a pointer to a void function that takes no parameters.
Corrected code:
void print() {
std::cout << "Hello World!\n";
}
void run_func(void (*func)()) {
func();
// or you can call the print function by (*func)();
}
int main() {
run_func(print);
// prints "Hello World!"
}

You could use std::function:
void print()
{
std::cout << "Hello World!" << std::endl;;
}
void run_func(std::function<void()> f) // f returns void and takes no parameters
{
f();
}
int main()
{
run_func(print);
}

Related

How can I call a function from an array of functions via its index?

A beginner's question I couldn't find answered online, likely because I don't know the terminology.
I want to call one of a list of procedures based on a computed index value. That is, given a '1', invoke firstProc(), '2' invokes secondProc() and so on.
All the procedures are void functions with no arguments.
I can implement that with switch/case, but what I'd prefer is something like:
void* action[2] {*firstProc, *secondProc};
(This compiles, but warns: invalid conversion from 'void (*)()' to 'void*')
and then later:
action[get_index()]();
The compiler objects that 'action' can't be used as a function.
This must be possible, right? I've tried several variations but I can't get past the use of the selected ('action[index]') as a function.
There are two equivalent ways to do what you want. The explanation is given as comments in the code snippets.
Method 1
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 1 can be executed here.
In method 1 above void (*a)() = foo; means that a is a pointer to a function that takes no parameter and also does not return anything.
Similarly, void (*b)() = foo2; means that b is a pointer to a function that takes no parameter and also does not return anything.
Next, void (*arr[2])() = { a, b}; means that arr is an array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter.
Method 2
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 2 can be executed here.
You need the correct syntax for your function pointer array. void(*func_ptr[])().
Example:
void func1() { std::cout << "Hallo" << std::endl; }
void func2() { std::cout << "World" << std::endl; }
// if you need a different signature for your functions like:
int func3(int n) { std::cout << "n1 " << n << std::endl; return n*2; }
int func4(int n) { std::cout << "n2 " << n << std::endl; return n*3; }
int main()
{
// array of function pointer which
// have no parameter and void as return value
void(*func_ptr[])()={ func1, func2 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
func_ptr[idx]();
}
// array of function pointers with int return value and int as
// parameter
int(*func_ptr2[])(int)={ func3, func4 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
std::cout << "retval: " << func_ptr2[idx](6) << std::endl;
}
}
I've stopped using function pointers (though they still can be useful).
I usually use std::function (and lambdas) when working with functions
Code for arrays of functions then look like this.
I used std::vector but std::array for fixed size should work fine too.
#include <vector>
#include <functional>
#include <iostream>
void some_function()
{
std::cout << "some function\n";
}
int main()
{
// std::function, abstraction of a function, function signature = template parameter, so void () is function returning a void, no parameters
// std::vector, runtime resizable array
// constructor : 4 time a lambda function printing out hello world.
std::vector<std::function<void()>> functions(4, [] { std::cout << "Hello World!\n"; } );
// easy syntax to assign an existing function to an index
functions[1] = some_function;
// replace a function in the vector with another one (lambda)
functions[2] = [] { std::cout << "booh\n"; };
// call function at index 0
functions[0]();
std::cout << "\n\n";
// or loop over all the functions and call them (classic for loop)
for (std::size_t n = 0; n < functions.size(); ++n) functions[n]();
std::cout << "\n\n";
// or loop over all the functions (range based for loop)
for (const auto& function : functions) function();
return 0;
}

Callback: function pointer as argument and passing an aditional agrument [duplicate]

This question already has answers here:
Explanation of function pointers
(4 answers)
Closed 2 years ago.
How to pass a function pointer as argument with an argument?
void A(){
std::cout << "hello" << endl;
}
void B(void (*ptr)()){ // function pointer as agrument
ptr(); // call back function "ptr" points.
}
void C(string name){
std::cout << "hello" << name << endl;
}
void D(void (*ptr2)(string name)){ // function pointer as agrument
ptr2(name); // error 1
}
int main(){
void (*p)() = A; // all good
B(p); // is callback // all good
void (*q)(string name) = C;
D(q)("John Doe"); // error 2
return 0;
};
errors:
1 - use of undeclared identifier 'name'
2 - called object type 'void' is not a function or function pointer
You should make D taking two parameters, one for the function pointer, one for the argument to be passed to function pointer. E.g.
void D(void (*ptr2)(string), const string& name){
ptr2(name);
}
then call it like
D(q, "John Doe");
name is a part of type declaration for ptr2 and is not a variable in D.
Tou are trying to call what is returned from D, which is void. , is used to separate arguments in C++.
Try this:
#include <iostream>
#include <string>
using std::endl;
using std::string;
void A(){
std::cout << "hello" << endl;
}
void B(void (*ptr)()){ // function pointer as agrument
ptr(); // call back function "ptr" points.
}
void C(string name){
std::cout << "hello" << name << endl;
}
void D(void (*ptr2)(string name), string name){ // function pointer and a string as agrument
ptr2(name);
}
int main(){
void (*p)() = A; // all good
B(p); // is callback // all good
void (*q)(string name) = C;
D(q, "John Doe"); // pass 2 arguments
return 0;
} // you don't need ; here

What is the difference between void f() and void(*f)()? And what are all the possible syntax to write when dealing with function pointers?

void F(void f(), void(*v)())
{
}
As far as I understand, the two parameters have the same type, both are a pointer to a function that takes nothing and returns void. What is these two ways of writing? If they are both the exact same thing, then why void f() is not popular as void(*f)()? The first one seems easier since it looks like how normal functions are written. Also what are all possible syntax someone can use when dealing with function pointers? Or where to find them? Here are some of the ones I was able to get:
#include <iostream>
#include <vector>
void func1()
{
std::cout << "func1\n";
}
void (*returnFunc1())()
{
return func1;
}
auto returnFunc1_2() -> void(*)()
{
return func1;
}
void func2(int x)
{
std::cout << "func2 " << x << "\n";
}
auto returnFunc2() -> void(*)(int)
{
return func2;
}
int func3(int, bool)
{
std::cout << "func3\n";
return 0;
}
int (*returnFunc3(long long))(int, bool)
{
return func3;
}
void func4(void f(), void(*v)())
{
std::cout << "func4\n";
}
void (*returnFunc4())(void(), void(*)())
{
return func4;
}
int main()
{
void (*funcPointer)() = func1;
funcPointer();
std::vector<void(*)()> v;
v.push_back(func1);
v.back()();
returnFunc2()(123);
returnFunc3(123)(456, true);
returnFunc4()(func1, func1);
}
Is there any other syntax that could be used? I'm just curious.
For example, what is the meaning of int (*(*foo)(void ))[3]? How to read such statements? Or where can I learn about reading such cryptic statements?

When to use this for class function in lambda

When should this be used in a lambda to call a class member function? I have an example below, where hello(); is called without this but this->goodbye(); does:
#include <iostream>
class A
{
void hello() { std::cout << "hello" << std::endl; }
void goodbye() { std::cout << "goodbye" << std::endl; }
public:
void greet()
{
auto hi = [this] () { hello(); }; // Don't need this.
auto bye = [this] () { this->goodbye(); }; // Using this.
hi();
bye();
}
};
int main()
{
A a;
a.greet();
return 0;
}
Is there any advantage to one way over the other?
Edit: The lambda for hello does not capture anything, yet it inherits functions that exist in the class scope. It cannot do this for members, why can it do this for functions?
this is more explicit and more verbose.
but it might be also required with variables which hide member (capture or argument):
auto goodbye = [](){}; // Hide method
auto bye = [=] (int hello) {
this->goodbye(); // call method
goodbye(); // call above lambda.
this->hello(); // call method
std::cout << 2 * hello; // show int parameter.
};

How to call a C++ class method, which is given as a parameter?

I'm trying to pass a method as a parameter to other method.
Magner.h:
Class Manager{
public:
timeCount(void (Manger::*function)(void));
void passedFuction();
}
In Manager.cpp, I'm trying to call timeCount by
timeCount(&Manager::passedFuction());
TimeCount Body:
void Manager::timeCount(void(Manager::*function)(void))
{
std::cout << "It works";
(*function)(); // here is error
}
ViusalStudio says:
void*Manager::*function)() operand of '*' must be a pointer
How should i correct it?
The example i was learing by was : http://www.cplusplus.com/forum/beginner/6596/
A pointer-to-member-function (pmf) is not a pointer. Let me repeat that:
A pointer-to-member-function is not a pointer.
To call a pmf, you have to provide it with the object you want to call it on. You probably want:
(this->*function)();
If you had another object obj of the right type, you could also use:
(obj.*function)();
The void (Manger::*function)(void) syntax is for member functions of Manager class, which cannot be used with functions outside the Manager class.
To fix this shortcoming, pass std::function<void(void)> instead, which would let you invoke itself using the regular function invocation syntax:
void Manager::timeCount(std::function<void(void)> f) {
std::cout << "It works";
f();
}
Here is a complete demo of how to call timeCount with member and non-member functions:
struct Manager {
string name;
void timeCount(std::function<void(void)> f) {
std::cout << "This is " << name << " manager" << endl;
f();
}
};
void foo() {
cout << "I'm foo" << endl;
}
struct Test {
int x;
void bar() {
cout << "I'm bar " << x << endl;
}
};
int main() {
Manager mgr {"time"};
mgr.timeCount(foo);
Test tst = {234};
mgr.timeCount(std::bind( &Test::bar, tst));
return 0;
}
Demo.
Since c++17, we have std::invoke:
std::invoke(function, this);
or
std::invoke(function, *this);
are both ok. Minimal demo:
#include <functional>
#include <iostream>
class Manager
{
public:
void timeCount(void (Manager::*function)(void));
void passedFuction()
{
std::cout << "call passedFunction\n";
}
};
void Manager::timeCount(void (Manager::*function)(void))
{
std::cout << "It works\n";
std::invoke(function, *this);
// (*function)(); // here is error
}
int main()
{
Manager a;
a.timeCount(&Manager::passedFuction);
}
It works
call passedFunction
live demo