In C++ it's possible to declare type aliases that are members of a class or struct:
struct Foo
{
// internal type alias
typedef int DataType;
// ...
};
Is there any way to do the same thing in Cython? I've tried the most obvious approach:
cdef struct Foo:
ctypedef int DataType
But this doesn't work:
Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++
cdef struct Foo:
ctypedef int DataType
^
------------------------------------------------------------
internal_typedefs_example.pyx:4:4: Expected an identifier, found 'ctypedef'
Is this just a fundamental limitation of Cython (I'm using v0.21.2), or is there a workaround?
Why bother with internal typedefs? There are several general reasons - this previous SO question covers a few of them.
The specific case I'm interested in is wrapping a set of templated C++ classes that look something like this:
struct FooDataset
{
typedef int DataType;
typedef float ReturnType;
// methods, other important stuff
};
struct BarDataset
{
typedef long DataType;
typedef double ReturnType;
// methods, other important stuff
};
template <class Dataset>
class DataProcessor{
DataProcessor(Dataset& input_data);
typedef typename Dataset::DataType T;
typedef typename Dataset::ReturnType R;
T getDataItem();
R computeSomething(); /* etc. */
// do some other stuff that might involve T and/or R
};
Having typedef(s) internal to the struct gives me better encapsulation since I only need to pass a single template parameter (the Dataset
class) rather than individually specifying the Dataset
plus T, R, ...
specific to that Dataset
type.
I realise that it's not too difficult to find workarounds for this case - I'm mostly just interested in getting a definitive answer as to whether or not internal typedefs are currently possible in Cython.
As far as I know this is not currently supported in Cython. But can't you just define it outside of the struct?
Cython is not currently designed as a replacement for C++, rather a way to speed up hot spots in python code. If you need something more involved just write it in C++ and expose python bindings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With