python中的函数模板

Muh*_*dri 2 c++ python templates function-templates

我想知道如何在 python 中使用与模板 < typename T>类似的代码,因为它在 C++ 代码示例中使用:

template <typename T>
unsigned int counting_bit(unsigned int v){
   v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
   v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
   v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
   return v;
}
Run Code Online (Sandbox Code Playgroud)

我将如何在 python 中以与 C++ 中提到的相同的方式使用变量 typename 类型转换对象?

mar*_*eau 7

通过使用 Python 的闭包执行以下操作,通过应用模板为特定类型创建函数,DeepSpace 的答案可以修饰为更像 C++。它还展示了在 Python 中获取和使用另一个变量的类型是多么容易。

def converter_template(typename):
    def converter(v):
        t = typename(v)  # convert to numeric for multiply
        return type(v)(t * 2)  # value returned converted back to original type

    return converter

int_converter = converter_template(int)
float_converter = converter_template(float)

print('{!r}'.format(int_converter('21')))    # '42'
print('{!r}'.format(float_converter('21')))  # '42.0'
Run Code Online (Sandbox Code Playgroud)


Dee*_*ace 5

只需将类型传递给函数。

例如,看到这个(无用的)函数:

def converter(x, required_type):
    return required_type(x)

converter('1', int)
converter('1', float)
Run Code Online (Sandbox Code Playgroud)