[Cython] template types
Dag Sverre Seljebotn
dagss at student.matnat.uio.no
Tue May 5 21:59:19 CEST 2009
Stefan Behnel wrote:
> 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.
I would feel it was inconvenient to use a seperate line to define
IntVector, then remember what name one gave it etc., rather than just
express what one wants. Templates quickly becomes second-nature in C++
and Java and this seems to work against that.
OTOH, this brings up another interesting question: What happens with
exporting templates to Python-land?
If there was indeed something very like typedef, but which also made the
templated type available Python-side...
I guess
IntVector = Vector<int>
would currently achieve that without any further magic though.
With [] or () or somesuch one could export some wrapper type for
"Vector" and look up the Vector[cython.int] type from Python-space,
however one must know compile-time which templates to instantiate for
Python access anyway. The template types to always instantiate and
export to Python could perhaps be embedded in the template declaration
syntax.
(I'd say that's a valid usecase eventually, but of course not something
to support at first. But it /does/ impact the chosen syntax quite
heavily as <> is ruled straight out.)
--
Dag Sverre
More information about the Cython-dev
mailing list