我想知道如何在 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/