在 C++ 中,可以声明作为类或结构成员的类型别名:
struct Foo
{
// internal type alias
typedef int DataType;
// ...
};
有没有办法在 Cython 中做同样的事情?我尝试过最明显的方法:
cdef struct Foo:
ctypedef int DataType
但这不起作用:
Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++
cdef struct Foo:
ctypedef int DataType
^
------------------------------------------------------------
internal_typedefs_example.pyx:4:4: Expected an identifier, found 'ctypedef'
这只是 Cython 的基本限制(我使用的是 v0.21.2),还是有解决方法?
为什么要费心内部类型定义呢?一般有几个原因——之前的这个问题 https://stackoverflow.com/q/759512/1461210涵盖了其中的一些。
我感兴趣的具体案例是包装一组模板化的 C++ 类,如下所示:
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
};
在结构内部拥有 typedef 可以给我更好的封装,因为我只需要传递一个模板参数(Dataset
类)而不是单独指定Dataset
plus T, R, ...
具体到那个Dataset
type.
我意识到找到这种情况的解决方法并不是太难 - 我主要感兴趣的是获得关于 Cython 目前是否可以使用内部 typedef 的明确答案。