Pointers to functions with unknown arguments?

Hi.
I was wondering if it is possible to create a generic function pointer that can pass any given arguments to the function it points to.
Basically:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
float Add(float a,float b){
    return a+b;
};
float Square(float a){
    return a*a;
};
int main(){
    float(*MyFunction)(???)=&Add;
    cout<<MyFunction(2,4);
    MyFunction=&Square;
    cout<<MyFunction(6);
    return 0;
};

Note: Until proven wrong, I do not think that the va_list system for "varying number-of-arguments" type function is a viable solution. How is the va_list system constructed anyway?

Thank you.
There is no such concept as generic function pointer, because generic function is declaration.
For example there cannot be class pointer , you can create pointer to object but not pointer on class because class is only declaration for compilator.
So you cannot create pointer on generic function, you can create pointer on instance function.
Pointer is object that keeps address of another object, but for example generic function does not appear in stack.
Last edited on
This hack comes into my mind.
Of course, you always have to know the signature of the function the pointer is pointing to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int f(double d, int x) {
	return x + d;
}

template<class ReturnType, class... Ts>
ReturnType callFunction(void *function, const Ts&... args) {	
	return reinterpret_cast<ReturnType(*)(Ts...)>(function)(args...);
}

int main() {
	void *function = reinterpret_cast<void*>(&f);
	
	std::cout << callFunction<int, double, int>(function, 1, 3) << std::endl;
	//Or just:
	std::cout << callFunction<int>(function, 1.0, 3) << std::endl;
}


Edit: probably there is some good boost or even std libs, that do the exact same thing, but this was more fun =)
Edit2: This could (probably) be "improved" further to use perfect forwarding.
Last edited on
Whoa, that's a good one. Although I probably don't fully understand the principles of variable argument functions, it looks like it should do the trick. Gonna test to see the idea in action.
Thanks for the fast answers.
Topic archived. No new replies allowed.