开发者

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 funct开发者_如何学运维ion that need to execute can refer to some other function at later point.


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.


Personally I think variable lists of arguments is a bad idea. It prevents you from using the compiler to do type checking and therefore make it easier to find bugs before any object code is produced.

I would therefore recommend that you find a way around this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜