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

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

问题描述

我正在寻找一种通过字符串输入调用不同函数的方法。



我有一个映射,将每个唯一的字符串绑定到函数指针和查找函数



现在的诀窍是,我需要一种方法来存储和返回指向至少具有不同返回类型的函数的指针,如果



从网络套接字获取字符串输入。

- >
找到并执行找到的函数 - >将结果直接送回套接字以便序列化和发送,而不是关心实际发生的事情。



这可行吗?如果没有,那么如何处理这个任务?

解决方案

这可以用不同的方式做一些样板代码。如果签名的数量足够小,您可以保存多个函数指针的向量(每个函数类型一个),然后映射函数名称与类型标识符(用于选择向量)和向量中的位置。 / p>

第二个选项是存储一个 boost :: variant (如果签名集合很小, 。您将需要提供一个访问者对象来评估函数(对于存储的每个函数类型)并产生结果。类型由 boost :: variant 类型管理,因此不需要将类型标记存储在地图中。



您还可以使用完全类型擦除并在映射中存储一个标记,确定要调用的函数的类型,并且使用 boost :: any 对象存储函数指针。您可以使用类型信息来检索指针并执行该函数,但您必须根据函数类型手动处理开关

$



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


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.

The usage would be:

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?

解决方案

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.

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.

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天全站免登陆