在Cython中是否可以使用C++风格的内部typedef
Are C++-style internal typedefs possible in Cython?
在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),还是有一个变通方法?
为什么要麻烦内部typedef?有几个普遍的原因——之前的SO问题涵盖了其中的一些原因。
我感兴趣的具体案例是包装一组模板化的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
类型的Dataset
加T, R, ...
。
我意识到,为这种情况找到解决办法并不太难——我最感兴趣的只是得到一个明确的答案,即Cython目前是否可以使用内部typedef。
据我所知,Cython目前不支持这一功能。但是你不能在结构之外定义它吗?
Cython目前并不是作为C++的替代品设计的,而是一种加速python代码热点的方法。如果您需要更多相关内容,只需用C++编写并公开python绑定即可。
在C++中,struct
是声明类的关键字。因此,内部typedef
可以在Cython中声明为:
cdef cppclass Foo:
ctypedef int DataType
相关文章:
- Qt VTK交互风格的信号到小部件
- 将函数类成员映射到类本身内部
- 我可以使用条件运算符初始化C风格的字符串文字吗
- Visual Studio 2019:插入多个C++风格的单行注释
- Boost Spirit,获取迭代器内部语义动作
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 内联函数中具有内部链接的全局变量
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- 卷曲bracers内部结构的声明
- 从函数角度看ID到文件路径的内部与外部映射
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 如何在pugixml中获取节点的内部XML
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- 方法内部但循环仍得到预期的不合格id错误C++
- C++:具有内部链接的正向声明常量
- 在Cython中是否可以使用C++风格的内部typedef
- 循环内部的迭代程序初始化是否被认为是糟糕的风格,以及为什么