Cython:基于调用签名的通用函数接口函数

Cython: Generic function interfacing functions based on call signature

基本上,想要编写两个函数,然后使用第三个通用函数,该函数纯粹根据给定的输入参数选择使用给定参数调用两个原始函数中的哪一个。例如

cdef fun1(int a):
    #do something

cdef fun1(float a):
    #do something

#roughly stealing syntax from fortran (this is the part I don't know how to do)
interface generic_function:
    function fun1
    function fun2


#Calling the functions
cdef int a = 2
cdef float b = 1.3
generic_function(a) #runs fun1
generic_function(b) #runs fun2

显然我可以用 if 语句来做到这一点,但对我来说这似乎效率不高。 感谢任何帮助,干杯。

这可以通过 [融合类型] (https://cython.readthedocs.io/en/latest/src/userguide/fusedtypes.html)

ctypedef fused int_or_float:
    int
    float

cdef generic_function(int_or_float a):
    if int_or_float is int:
        fun1(a)
    else:
        fun2(a)

if 语句在 Cython 编译函数时被评估(您可以通过查看生成的 c 代码来验证这一点)因此不是性能问题。