简体   繁体   English

C ++函数指针“ base”

[英]c++ function pointer 'base'

I am converting fortran code to C++ and wanted to find a right option for function-pointer. 我正在将fortran代码转换为C ++,并想为函数指针找到正确的选项。

The fortran code is: for two different cases, it passes two different kinds of function-pointers to another function. fortran代码是:对于两种不同的情况,它将两种不同类型的函数指针传递给另一个函数。 These function pointers have different interfaces. 这些函数指针具有不同的接口。 In C++, I need to specify interface of function-pointer and hence it is not straightforward. 在C ++中,我需要指定函数指针的接口,因此它并不简单。 Can someone suggest, if C++ functor or something else, that would be useful? 有人可以建议使用C ++函子或其他工具吗? I wish I could use something like 'void (function) pointer' and then 'cast', but I really don't know. 我希望可以使用“ void(函数)指针”然后再使用“ cast”之类的方法,但是我真的不知道。 Thanks in advance. 提前致谢。

EDIT: minimal example in fortran 编辑:fortran中的最小示例

Fortran Fortran

if(option1) then
call myfunc( abc_function_pointer,otherarguments)
else
call myfunc( xyz_function_pointer, otherarguments) 
endif

where, these functions are (in C++) 这些函数在哪里(在C ++中)

void (*abc_function_pointer)(int, float) //in c++
void (*xyz_function_pointer)(int, int, int) //in c++

Generally speaking, this is a bad idea. 一般来说,这是一个坏主意。 Consider - what is myfunc going to do with this function pointer? 考虑myfunc与该函数指针有什么关系? What happens if you pass it abc_function_pointer , but it tries to call it with three int s? 如果您将其传递给abc_function_pointer ,但它尝试使用三个int进行调用,会发生什么? Or vice versa? 或相反亦然?

Without knowing what you're using this for, it's hard to suggest what you should do. 不知道您要使用它做什么,很难建议您应该做什么。 Typically you would want to factor out the common interface between abc_function_pointer and xyz_function_pointer , so myfunc always calls a function with the same type and interface. 通常,您可能希望排除abc_function_pointerxyz_function_pointer之间的公共接口,因此myfunc始终调用具有相同类型和接口的函数。 You can insert a shim function that converts between the common interface and that of abc_function_pointer or xyz_function_pointer . 您可以插入一个shim函数,该函数在公共接口和abc_function_pointerxyz_function_pointer的公共接口之间转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM