Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function pointer to a function which has variable argument list

Can we have a function pointer which points to a function which use a varying argument list? For example, lets say i need to select a function among a number of functions based on some input T 'input'. Can i use a STL map somthing like this??

template<typename T>
map<T, T (*)(T, ...)> func_map;

If this is possible can you tell me doing so will be right thing to do with design perspective.


[Edit] Actually i have a set of algorithmic functions and i have a message field. I need to select this algorithmic function based on few bytes values on this msg. I was thinking to use hash_map with a key value w.r.t. the pointer to that algorithmic function. i wanted to be very fast as per performance, what can be bast way to implement this.

Also, the reason why i am not selecting simple if-else or switch block for this is because the value which tell us the function that need to execute can refer to some other function at later point.

like image 745
HokageSama Avatar asked Sep 08 '11 12:09

HokageSama


People also ask

Can we pass a variable argument list to a function at?

Every actual argument list must be known at compile time. In that sense it is not truly a variable argument list.

How do you pass pointer variables as function arguments?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

Is a function pointer a variable?

A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.

Which function accepts a variable number of arguments?

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.


1 Answers

Yes, it is possible to do this, but you probably shouldn't. There are a number of problems with variadic functions, including:

  • All types passed must be POD types or the behavior is undefined
  • There is no type safety whatsoever. If you pass the wrong type, you will cause undefined behavior.

I would recommend you find another approach. If you give more specifics on why you need to do this, perhaps someone can give you a better option.

like image 149
Dark Falcon Avatar answered Oct 18 '22 16:10

Dark Falcon