模板中的 Cython C++ 静态方法 class

Cython C++ static methods in a template class

问题

我有一个 C++ 模板 class,它有一个静态方法。它看起来或多或少是这样的:

template<typename T>
class Foo {
    static std::shared_ptr<Foo<T>> doSth();
}

所以在 C++ 中你可以这样称呼它:Foo<Int>::doSth();。然而,在 Cython 中,调用静态方法的方法是使用 classname 作为命名空间:

cdef extern from "Bar.h" namespace "Bar":
    shared_ptr[Bar] doSth()  # assuming shared_ptr is already declared

但这没有模板的概念。显然,简单地将 Foo<T> 作为命名空间传递是行不通的,因为它在 C++ 中转换为 Foo<T>::doStr(),没有具体类型替代 T.

问题

你会如何在 Cython 中做到这一点?有办法或解决方法吗?

注意:这个答案在写的时候是正确的(并且仍然有效)但是你现在应该使用 来正确地做到这一点。


我认为您不能直接在 Cython 中完成。您可以创建普通(非静态方法)c++ 模板函数的非常薄的包装器

template <typename T>
std::shared_ptr<Foo<T>> Foo_T_doSth<T>() {
   return Foo<T>::doSth();
}

然后用 Cython 包装这个方法

cdef extern from "..."
    shared_ptr[T] Foo_T_doSth[T]()

顺便说一句,在 Cython 中包装静态方法的推荐方法看起来是(来自 https://groups.google.com/forum/#!topic/cython-users/xaErUq2yY0s

cdef extern from "...":
   cdef Foo_doSth "Foo::doSth"()  # not declared as a memeber

(通过指定要用作字符串的实际函数)。这对你没有帮助,因为它不处理模板。可能是我在您尝试的方式上误导了您...

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

http://docs.cython.org/en/latest/src/userguide/wrapping_CPlusPlus.html#static-member-method