python - python中的函数模板

标签 python c++ templates function-templates

我想知道如何在 python 中使用与 template < 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;
}

我如何在 python 中使用与 C++ 中提到的相同的方式对具有变量类型名的对象进行类型转换?

最佳答案

DeepSpace 的答案可以通过使用 Python 的闭包来做类似以下的事情来修饰,使事情更像 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'

关于python - python中的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843599/

相关文章:

javascript - flask-security ajax 注销导致 session 错误

python - Azure ML 文件数据集 mount() 速度慢且下载数据两次

c++ - 类名前的宏

c++ - 这些 shared_ptr 实例之间的区别?

C++ 方法调用模板函数无法调用重载方法

python - 获取列表中的字典,其中键为 :value pairs are in another list of dictionaries

python - 类型错误 : list object is not an iterator

c++ - 带有模板的字符串堆栈?

C++ PlaySound() 给出错误

c++ - 矩阵转置模板