Create a function pointer which takes a function pointer as an argument - c++

How to create a function pointer which takes a function pointer as an argument (c++)???
i have this code
#include <iostream>
using namespace std;
int kvadrat (int a)
{
return a*a;
}
int kub (int a)
{
return a*a*a;
}
void centralna (int a, int (*pokfunk) (int))
{
int rezultat=(*pokfunk) (a);
cout<<rezultat<<endl;
}
void main ()
{
int a;
cout<<"unesite broj"<<endl;
cin>>a;
int (*pokfunk) (int) = 0;
if (a<10)
pokfunk=&kub;
if (a>=10)
pokfunk=&kvadrat;
void (*cent) (int, int*)=&centralna; // here i have to create a pointer to the function "centralna" and call the function by its pointer
system ("pause");
}

you will find it easier to typedef function pointers.
typedef int (*PokFunc)(int);
typedef void (*CentralnaFunc)(int, PokFunc);
...
CentralnaFunc cf = &centralna;

You need to use the function pointer type as the type of the parameter:
void (*cent) (int, int (*)(int)) = &centralna

void (*cent)(int,int (*) (int))=&centralna;

Related

Examples about function pointer and callback function definition

I'm learning about callback function in C++ and have some problems in understanding the initialization of a callback function such as
typedef void (CALLBACK *name)(int,int);
I think it looks very similar to the declaration of function pointer like this:
typedef void (*name)(int,int);
I have a simple example about how to call a function inside another function using the declaration of function pointer. The example converts a string to int and compare with anoter int. Then tells which one is bigger:
#include <stdio.h>
#include <stdlib.h>
int StrToInt(char* inputchar) //converting function
{
int outputint;
outputint = atoi(inputchar);
return outputint;
}
typedef int(*p)(char*); //declare function pointer
void IntCompare(p FuncP, char* inputchar, int b) //comparing function
{
int a;
a = FuncP(inputchar); //call converting function using function pointer
if (a<b)
{
printf("%d is bigger\n", b);
}
else
{
printf("%d is bigger\n", a);
}
}
void main()
{
char* StrNum = "1234";
p FuncP; //creat a function pointer
FuncP = StrToInt; //point to converting function
IntCompare(FuncP, StrNum, 21);
}
What I'm asking is:
Could somebody give me a similar example about how to use typedef void (CALLBACK *name)(int,int);? Please help me understand when and how to use it. Thank you for your attention.
CALLBACK is macro. It relates to callback functions but it's not the same. You can start looking at implementation of callback functions in C.
qsort for example uses this technique. qsort is a single function which can sort any array. But you have to tell qsort how to compare different data types. That's done by passing a function pointer to qsort.
int compare_int(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int compare_string(const void * a, const void * b)
{
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa, pb);
}
int main ()
{
int int_array[] = { 3, 2, 1 };
int count = sizeof(int_array) / sizeof(int);
qsort(int_array, count, sizeof(int), compare_int);
const char *string_array[] = { "234","123","456" };
count = sizeof(string_array) / sizeof(char*);
qsort(string_array, count, sizeof(char*), compare_string);
return 0;
}
Of course in C++ we use std::sort, which uses templates instead.
But we still need to pass functions in C++. See for example, the implementation of for_each
template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
for (; first != last; ++first) {
f(*first);
}
return f;
}
Usage:
std::vector<int> nums{ 3, 4, 2, 8, 15, 267 };
auto print = [](const int& n) { std::cout << " " << n; };
std::for_each(nums.begin(), nums.end(), print);
std::cout << '\n';

Accessing entry of Array of function pointers, within a class C++

I wrote a simple class that performs basic arithmetic operations using a method that receives an index and two values to compute.
The index indicates which operation to perform in a table that contains pointers to functions.
Here is my code:
#include <iostream>
using namespace std;
class TArith
{
public:
static const int DIV_FACTOR = 1000;
typedef int (TArith::*TArithActionFunc)(int,int);
struct TAction
{
enum Values
{
Add,
Sub,
count,
};
};
int action(TAction::Values a_actionIdx, int a_A, int a_B)
{
return ( this->*m_actionFcns[a_actionIdx] )(a_A,a_B);
}
private:
int add(int a_A, int a_B)
{
return a_A + a_B ;
}
int sub(int a_A, int a_B)
{
return a_A - a_B ;
}
static TArithActionFunc m_actionFcns[TAction::count];
int m_a;
int m_b;
};
TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = {
TArith::add,
TArith::sub
};
void main(void)
{
TArith arithObj;
int a=100;
int b=50;
for(int i = 0 ; i <TArith::TAction::count ; ++i)
{
cout<<arithObj.action( (TArith::TAction::Values)i,a,b )<<endl;
}
cout<<endl;
}
Compiler says:
'TArith::add': function call missing argument list; use '&TArith::add' to create a pointer to member
'TArith::sub': function call missing argument list; use '&TArith::sub' to create a pointer to member
why do I need to use the & symbol?
TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = {
TArith::add,
TArith::sub,
TArith::mul,
TArith::div
};
Correct syntax for a pointer to a member function f of a class C is &C::f. You're missing the leading &.
Try:
TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = {
&TArith::add,
&TArith::sub,
&TArith::mul,
&TArith::div
};

why my definition of a function that returns the pointer to another function doesn't work?

I am learning pointer to functions, and want to define a function that has the return value which is the pointer to another function. In my sample program fun is trying to return a pointer that points to next. However, the program fails to compile. I have written my thought in the comment, any idea where is the problem?
#include <iostream>
using namespace std;
int next(int );
//define next_fp as a pointer to a function that takes an int and return an int
typedef int (*next_fp)(int);
//define a function that returns a pointer to a function that takes an int and return an int
next_fp fun(next);
int main()
{
cout << fun(next)(5) <<endl;
return 0;
}
int next(int n) {
return n+1;
}
next_fp fun(next) {
//fun's return type is next_fp, which is a pointer to
//a function that take an int and return an int.
return next;
}
next_fp fun(next);
When declaring a function, you must declare the type of the arguments. Try:
next_fp fun(next_fp next);
// ...
next_fp fun(next_fp next) {
// ...
}
As stated in the comments, you should avoid using for a parameter a name already used in the same scope for a function. You may add a trailing _ to mark function parameters (my personal convention, feel free to use yours):
next_fp fun(next_fp next_);
Parameter is not declared properly in function declaration next_fp fun(next); (and definition); next is not a type, it's a name of function.
You should change it to:
next_fp fun(next_fp);
and for definition:
next_fp fun(next_fp next) {
//fun's return type is next_fp, which is a pointer to
//a function that take an int and return an int.
return next;
}
This works for me:
#include <iostream>
using namespace std;
int next(int );
//define next_fp as a pointer to a function that takes an int and return an int
typedef int (*next_fp)(int);
//define a function that returns a pointer to a function that takes an int and return an int
next_fp fun(next_fp);
int main()
{
return 0;
cout << (fun(next))(5) <<endl;
}
int next(int n) {
return n+1;
}
next_fp fun(next_fp www) {
//fun's return type is next_fp, which is a pointer to
//a function that take an int and return an int.
return www;
}

How to define pointer to pointer to function and how to use it in C++?

My question is how to translate the following example? Is this a function, that returns int pointer?
int* (*function)(int, (int (*k)(int *)));
And can I can't write program that use it?
Thanks in advance!
It is a function-pointer
The function returns a pointer to an int
The function's first arg is an int
The function's second arg is a function-pointer k
k returns an int
k takes a pointer to an int as argument
Sure you can use that in your program. It is not too unusual. There are much worse declarations i have seen.
I renamed your "function" to "F" for clarity. Then you can write:
int* (*F)(int, int (*kFunc)(int *) );
Alternative:
typedef int (*kFunc)(int *);
int* (*F)(int, kFunc);
There are a lot of ways to use pointer to a function, may be a pattern such as Factory could take advantage of the function pointer to create new objects.( Look here : http://www.codeproject.com/Articles/3734/Different-ways-of-implementing-factories)
May be this piece of code could help you and give ideas of how powerfull can be working with function pointers.
#include <stdio.h>
#include <stdlib.h>
#include <map>
// Define the func ptrs
typedef void (*TFunc)(const char *, int);
typedef int (*TFunc2)(int);
int return_value(int i)
{
return i * 5;
}
void a( const char *name, int i )
{
printf ("a->%s %d\n\n", name, i);
}
void b( const char *name, int i)
{
printf ("b->%s %d\n\n", name, i);
}
struct test
{
const char *name;
int i;
TFunc func;
};
static test test_array[2] =
{
{ "a", 0, a },
{ "b", 1, b },
};
int main(int argc, char **argv, char** envp)
{
// Check the simple case, pointer to a function
TFunc fnc = a;
TFunc2 fnc2 = return_value;
fnc("blabla", 5);
fnc = b;
fnc("hello!", 55);
printf ("%d\n\n",fnc2(5));
//Check arrays of structs when there is a pointer to a fnc
test_array[0].func(test_array[0].name, test_array[0].i);
test_array[1].func(test_array[1].name, test_array[1].i);
//Handle a map of functions( This could be a little implementation of a factory )
typedef std::map<int, TFunc > myMap;
myMap lMap;
lMap.insert(std::make_pair(5, a));
lMap.insert(std::make_pair(2, b));
if( lMap.find( 5 ) != lMap.end() )
{
lMap[5]("hello map 5", 1);
}
myMap::iterator lItFind = lMap.find(2);
if( lItFind != lMap.end() )
{
lItFind->second("hello map 2", 2);
}
return(0);
}
I hope that this helps you.
You should remove extra parentheses, this is correct version:
int* (*function)(int, int (*k)(int *));
explanation (using right-left rule):
int* (*fn)(int, int (*k)(int *));
fn : fn is a
(*fn) : pointer
(*fn)(int, int (*k)(int *)) : to a function taking as arguments
- an int and
- function pointer
which takes a pointer to int
and returns int
int* (*fn)(int, int (*k)(int *)) : and returns a pointer to int
below is a short example on how to use it, also you ask for How to define pointer to pointer to function so below this is also included.
http://coliru.stacked-crooked.com/a/d05200cf5f6397b8
#include <iostream>
int bar(int*) {
std::cout << "inside bar\n";
return 0;
}
int* foo(int, int (*k)(int *)) {
std::cout << "inside foo\n";
k(nullptr);
return nullptr;
}
int main() {
int* (*function)(int, int (*k)(int *));
function = foo;
function(0, bar);
// Now, as you asked for, a pointer to pointer to above function
decltype(function) *pff;
pff = &function;
(*pff)(0, bar);
}

Pointer to function member and non-member

Abstract
I have a class that stores a optimization problem and runs a solver on that problem.
If the solver fails I want to consider a sub-problem and solve using the same solver (and class).
Introduction
An optimization problem is essencially a lot of (mathematical) functions. The problem functions are defined outside the class, but the sub-problem functions are defined inside the class, so they have different types (e.g. void (*) and void (MyClass::*).
At first I thought that I could cast the member function to the non-member pointer-to-function type, but I found out that I cannot. So I'm searching for some other way.
Example Code
An example code to simulate my issue:
#include <iostream>
using namespace std;
typedef void (*ftype) (int, double);
// Suppose foo is from another file. Can't change the definition
void foo (int n, double x) {
cout << "foo: " << n*x << endl;
}
class TheClass {
private:
double value;
ftype m_function;
void print (int n, double x) {
m_function(size*n, value*x);
}
public:
static int size;
TheClass () : value(1.2), m_function(0) { size++; }
void set_function (ftype p) { m_function = p; }
void call_function() {
if (m_function) m_function(size, value);
}
void call_ok_function() {
TheClass ok_class;
ok_class.set_function(foo);
ok_class.call_function();
}
void call_nasty_function() {
TheClass nasty_class;
// nasty_class.set_function(print);
// nasty_class.set_function(&TheClass::print);
nasty_class.call_function();
}
};
int TheClass::size = 0;
int main () {
TheClass one_class;
one_class.set_function(foo);
one_class.call_function();
one_class.call_ok_function();
one_class.call_nasty_function();
}
As the example suggests, the member function can't be static. Also, I can't redefine the original problem function to receive an object.
Thanks for any help.
Edit
I forgot to mention. I tried changing to std::function, but my original function has more than 10 arguments (It is a Fortran subroutine).
Solution
I made the change to std::function and std::bind as suggested, but did not went for the redesign of a function with more 10 arguments. I decided to create an intermediate function. The following code illustrates what I did, but with fewer variables. Thanks to all.
#include <iostream>
#include <boost/tr1/functional.hpp>
using namespace std;
class TheClass;
typedef tr1::function<void(int *, double *, double *, double *)> ftype;
// Suppose foo is from another file. Can't change the definition
void foo (int n, int m, double *A, double *x, double *b) {
// Performs matrix vector multiplication x = A*b, where
// A is m x n
}
void foo_wrapper (int DIM[], double *A, double *x, double *b) {
foo(DIM[0], DIM[1], A, x, b);
}
class TheClass {
private:
ftype m_function;
void my_function (int DIM[], double *A, double *x, double *b) {
// Change something before performing MV mult.
m_function(DIM, A, x, b);
}
public:
void set_function (ftype p) { m_function = p; }
void call_function() {
int DIM[2] = {2,2};
if (m_function) m_function(DIM, 0, 0, 0);
}
void call_nasty_function() {
TheClass nasty_class;
ftype f = tr1::bind(&TheClass::my_function, this, _1, _2, _3, _4);
nasty_class.set_function(f);
nasty_class.call_function();
}
};
int main () {
TheClass one_class;
one_class.set_function(foo_wrapper);
one_class.call_function();
one_class.call_nasty_function();
}
PS. Creating a std::function with more than 10 variables seemed possible (compiled, but I didn't test) with
#define BOOST_FUNCTION_NUM_ARGS 15
#include <boost/function/detail/maybe_include.hpp>
#undef BOOST_FUNCTION_NUM_ARGS
But creating a std::bind for more than 10 arguments does not seem as easy.
std::function, std::bind, and lambdas are what you are looking for. In short, function pointers are very bad things and should be burned in fire. In long, std::function can store any function object which can be called with the correct signature, and you can use std::bind or a lambda to generate a function object that calls your member function quickly and easily.
Edit: Then you will just have to roll your own std::function equivalent that supports more than 10 arguments.