3

I would like to know how would I use similar code to template < typename T> in python, as it is used in the C++ code example:

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;
}

How would I typecast objects with variable typename in python the same way as it is mentioned in C++?

Muhammad Ali Qadri
  • 606
  • 2
  • 8
  • 21

2 Answers2

8

DeepSpace's answer could be embellished to make things more C++-like by using Python's closures to do something like the following — sometimes called a factory function or a function factory — to create functions for specific types by applying the template. It also shows how easy it is in Python to obtain and use the type of another variable.

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'
martineau
  • 119,623
  • 25
  • 170
  • 301
6

Just pass the type to the function.

For example, see this (useless) function:

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

converter('1', int)
converter('1', float)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154