指针映射到不同的返回类型和签名功能 [英] map of pointers to functions of different return types and signatures

查看:178
本文介绍了指针映射到不同的返回类型和签名功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方法以字符串输入调用不同的功能。

I am looking for a way to call different functions by a string input.

我有一个地图,每一个独特的绳结一个函数指针和查找功能,搜索地图,如发现返回一个指针。

I have a map that ties each unique string to a function pointer and a lookup function to search the map and return a pointer if found.

现在的诀窍是,我需要一种方法来存储和返回指针的函数至少有不同的返回类型,如果可能的话,还与不同的签名。

Now the trick is, I need a way to store and return pointers to functions with at least different return types, if possible, also with different signatures.

的用法是:

获取从网络插座一个字符串输入 - >
找到并执行发现功能 - >推的结果直接回到套接字进行序列化和发送,不关心究竟发生了什么。

Get a string input from a network socket -> find and execute the found function -> shove the result straight back into the socket to be serialized and sent, not caring what actually happened.

这是可行的?如果不是,怎么会处理这个任务?

Is this doable? If not, how would one approach this task?

推荐答案

这可以带着几分以不同的方式样板code来完成的。如果签名的数量足够小,则可以保持功能的指针的多个载体,该函数名与类型标识符(用于选择向量)映射(每个功能类型一个),然后在地图和向量中的位置。

That can be done with a bit of boilerplate code in different ways. If the number of signatures is small enough you can hold multiple vectors of function pointers (one per function type) and then a map that maps the function name with a type identifier (used to select the vector) and the position within the vector.

第二个选项是(同​​样,如果设定的签名小)存储的boost ::变种。您会需要提供用于评估功能(存储每个功能型)并产生结果的访问者对象。类型由的boost ::变异类型,这样管理就没有必要在类型标记存储在地图中。

The second option would be to store a boost::variant (again, if the set of signatures is small). You would need to provide a visitor object that evaluates the function (for each function type stored) and yields the result. The type is managed by the boost::variant type so there would be no need for the type tag to be stored in the map.

您还可以使用完整的类型擦除并存储在地图上的标记确定的函数类型被称为和的boost ::任何对象存储函数指针。您可以使用类型信息检索指针和执行的功能,但你必须根据功能类型手工处理的开关。

You can also use full type erasure and store in the map a tag determining the type of function to be called and a boost::any object storing the function pointer. You can use the type information to retrieve the pointer and execute the function, but you will have to manually handle the switch based on function type.

最简单的方法,在另一方面,是写具有固定接口适配器。然后,只需指针存储地图中的适配器。

The simplest approach, on the other hand, is to write adapters that have a fixed interface. Then just store the pointers to the adapters in the map.

这篇关于指针映射到不同的返回类型和签名功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆