pio*_*ocz 11 c++ templates cython
我在C++中有一个模板类,它有一个静态方法.它看起来或多或少像这样:
template<typename T>
class Foo {
static std::shared_ptr<Foo<T>> doSth();
}
Run Code Online (Sandbox Code Playgroud)
所以在C++中你会称它为:Foo<Int>::doSth();.但是在Cython中,调用静态方法的方法是使用classname作为命名空间:
cdef extern from "Bar.h" namespace "Bar":
shared_ptr[Bar] doSth() # assuming shared_ptr is already declared
Run Code Online (Sandbox Code Playgroud)
但这没有模板的概念.显然,简单地Foo<T>作为命名空间传递是行不通的,因为它转换为Foo<T>::doStr()C++,没有具体的类型代替T.
你会怎么在Cython中做到这一点?有办法还是解决方法?
Cython现在直接支持静态方法; 命名空间hack不再是必需或推荐的.
cdef extern from "Foo.h":
cdef cppclass Foo[T]:
@staticmethod
shared_ptr[Foo[T]] doSth() # assuming shared_ptr is already declared
cdef shared_ptr[Foo[int]] shared_ptr_value = Foo[int].doSth()
Run Code Online (Sandbox Code Playgroud)
http://docs.cython.org/en/latest/src/userguide/wrapping_CPlusPlus.html#static-member-method
注意:这个答案在编写时是正确的(并且仍然有效),但您现在应该使用@Robertwb对此问题的答案来正确执行此操作。
我认为你不能直接在 Cython 中完成它。您可以创建普通(非静态方法)C++ 模板函数的非常薄的包装器
template <typename T>
std::shared_ptr<Foo<T>> Foo_T_doSth<T>() {
return Foo<T>::doSth();
}
Run Code Online (Sandbox Code Playgroud)
然后将此方法包装在 Cython 中
cdef extern from "..."
shared_ptr[T] Foo_T_doSth[T]()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在 Cython 中包装静态方法的推荐方法看起来是(来自https://groups.google.com/forum/#!topic/cython-users/xaErUq2yY0s)
cdef extern from "...":
cdef Foo_doSth "Foo::doSth"() # not declared as a memeber
Run Code Online (Sandbox Code Playgroud)
(通过指定要用作字符串的实际函数)。这对您没有帮助,因为它不处理模板。可能是我在你尝试的方式上给了你错误的建议......
| 归档时间: |
|
| 查看次数: |
1817 次 |
| 最近记录: |