[Cython] template types
Stefan Behnel
stefan_ml at behnel.de
Tue May 5 21:23:57 CEST 2009
Dag Sverre Seljebotn wrote:
> Stefan Behnel wrote:
>> Imagine you could write
>>
>> cdef class MyType<T>(object):
>> # type T gets defined in the class scope to make the parser happy
>> cdef T* my_attribute
>> def __init__(self, T value):
>> self.my_attribute = malloc(sizeof(T)*1000)
>> self.my_attribute[100] = value
>> def T do_work(self, T input):
>> return input + self.my_attribute[100]
>>
>> o = MyType<int>(20) # first occurrence creates/registers the type
>> o.do_work(18)
>>
>> ctypedef MyType<int> MyIntType # reuses the type and provides a name
>>
>> cdef MyIntType ot = MyIntType(25)
>> print ot.do_work(19)
>>
>> ctypedef MyType<double> MyDType # creates and defines a new type
>>
>> I'm not sure if a common base class would make sense here, something that
>> would just implement everything that doesn't depend on T. But maybe that's
>> overkill already. And most stuff *will*
>
> - Using < and > makes the parser more complicated, while [] must already
> be parsed. (in C++ there's the mess of having to write "vector<vector<int>
>> ", note the space, because there would be some problem with the >>
> operator and the parser otherwise).
What about avoiding this problem all-together? We could require a ctypedef
in the beginning, which would alleviate the need for a syntax that works
well in expressions.
Stefan
More information about the Cython-dev
mailing list