how do we create dynamic table of pointers to functions ?
i tried this in C++ , but it doesn't work , syntax error!
int (**ptr)(int , int )=new int [size] (int, int ) ;
please help.




Posted 19 March 2012 - 03:20 PM
#include <iostream>
using namespace std;
int add(int x, int y) { return x+y; }
typedef int (*func)(int, int);
int main() {
int (*ptr)(int, int);
ptr = add;
cout << ptr(2,3) << endl;
const int size = 3;
func *array = new func[size];
array[0] = add;
cout << array[0](4,5) << endl;
return 0;
}
Posted 20 March 2012 - 03:12 AM
typedef int (*Function_ptr_type) (int, int);
Function_ptr_type* ptr = new Function_ptr_type[size];
auto ptr = new std::function<int(int,int)>[size];
This post has been edited by Karel-Lodewijk: 20 March 2012 - 03:29 AM
Posted 21 March 2012 - 02:39 PM
#include <iostream>
#include <functional> //for the polymorphic wrapper
using namespace std;
int add_two(int a, int b ) {
return a+b;
}
int main ()
{
//w is a wrapper, and from here it refers to add_two function
//note that the return type and the arguments of the wrapper and function it refers to must be the same, or of the types that are convertible to it
function<int (int, int)> w = &add_two;
cout<<w(2, 3)<<endl;
return 0;
}
#include <iostream>
#include <functional>
using namespace std;
int add_two(int a, int b ) {
return a+b;
}
int subtract_two(int a, int b ) {
return a-b;
}
int main ()
{
auto p = new function<int (int, int)>[2]; //allocate memory for two wrappers
//function<int (int, int)>* p = new function<int (int, int)>[2]; <- Without auto, you had to write this
//now, these pointers must refer to functions we have
p[0] = &add_two;
p[1] = &subtract_two;
cout<<"Add: 2+3 = "<<p[0](2,3)<<endl;
cout<<"Subtract: 3-2 = "<<p[1](3,2)<<endl;
delete[] p;
return 0;
}
This post has been edited by Anarion: 21 March 2012 - 04:44 PM
