2014-09-26 62 views
1

我有一個模板A類和派生類B:如何在Cython中編寫派生模板cpp類的構造函數?

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不是模板,那麼就沒有錯誤。有關如何正確執行此操作的任何建議?

回答

0

我不能告訴你爲什麼 Cython期望一個空的構造函數,但它確實如此。

請注意,問題與模板無關;問題純粹是Cython需要一個空的構造函數。嘗試刪除模板並保留它,以便構造函數具有參數並且錯誤仍然存​​在。

一種方式來做到這一點是假裝它的存在:

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>(); 

錯誤,如果空構造是不斷無意中調用,所以它的安全......這只是醜陋。

當你有這樣的,這樣的代碼:

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

作品如你所願。

相關問題