如何在Cython中编写派生模板cpp类的构造函数?

时间:2014-09-26 15:22:39

标签: inheritance constructor cython

我有一个模板类A和一个派生类B:

test.hpp

#pragma once

namespace test {

template <typename T1>
class A {
    T1 a;
public:
    A(T1 _a) : a(_a) { }
    virtual ~A() { }
};

class B : public A<int> {
public:
    B(int a) : A<int>(a) { }
    virtual ~B() { }
};

}

可以编译。

然后我尝试编写一个cython脚本来公开A和B:

test.pyx

# distutils: language = c++

cdef extern from "test.hpp" namespace "test":
    cdef cppclass A[T1]:
        A(T1)
    cdef cppclass B(A):
        B(int)

然后我收到编译错误:

test.pyx:7:10: no matching function for call to A::A()
Traceback (most recent call last):
  File "setup.py", line 8, in <module>
    ext_modules = cythonize("test.pyx"),
  File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 825, in cythonize
    cythonize_one(*args[1:])
  File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 944, in cythonize_one
    raise CompileError(None, pyx_file)

我注意到如果类A不是模板,那么就没有错误。关于如何正确地做到这一点的任何建议?

1 个答案:

答案 0 :(得分:0)

我无法告诉你为什么 Cython期待一个null构造函数,但确实如此。

请注意,问题与模板无关;问题纯粹是Cython想要一个null构造函数。尝试删除模板并保留它,以便构造函数有一个参数,并且错误仍然存​​在。

一种方法是假装它存在:

cdef cppclass A[T1]:
    A()
    A(T1)
cdef cppclass B(A[int]):
    B(int)

会出错
FILENAME: error: no matching function for call to ‘test::A<int>::A()’
   __pyx_v_a = new test::A<int>();

如果无意中调用了null构造函数,那么它是安全的...它只是丑陋。

当你有这个时,代码如:

cdef A[int] *a = new B(4)

按预期工作。