简体   繁体   English

使用 boost.python 导出 c++ 多态函数的智能方法

[英]A smart way to export c++ polymorphic functions with boost.python

I have a highly polymorphic c++ function that can be called with nearly 20 diferent types.我有一个高度多态的 c++ function 可以用近 20 种不同的类型调用。

In order to expose it to python I'm doing something like this:为了将它暴露给 python 我正在做这样的事情:

#include originalFunctionNamespace.hpp

template<class T>
    T foo(T x)
    {
        return orignalFunctionNamespace::foo(x);
    }

but then to call them from python I have to specialize the functions with each type they support:但是然后要从 python 调用它们,我必须使用它们支持的每种类型来专门化函数:

BOOST_PYTHON_MODULE(module_foo)
{
    def("foo", foo<orignalFunctionNamespace::type1>);
    def("foo", foo<orignalFunctionNamespace::type2>);
    def("foo", foo<orignalFunctionNamespace::type3>);
    def("foo", foo<orignalFunctionNamespace::type4>);
    def("foo", foo<orignalFunctionNamespace::type5>);
    def("foo", foo<orignalFunctionNamespace::type6>);
    def("foo", foo<orignalFunctionNamespace::type7>);
    ...
    ...
    ...
    def("foo", foo<orignalFunctionNamespace::typeN>);
}

This works, but I can't stop thinking that there must be a smarter way to do it.这行得通,但我不能停止认为必须有更聪明的方法来做到这一点。 Since I have to do it for many many functions, things are getting big and super repetitive.由于我必须为许多功能执行此操作,因此事情变得越来越大并且超级重复。 Any suggestions?有什么建议么?

Looks like a possible use for typelist magic, to me.对我来说,这看起来像是 typelist 魔法的一种可能用途。

If you're using (or can use) the new C++0x standard, you can write something like this:如果您正在使用(或可以使用)新的 C++0x 标准,您可以编写如下内容:

template <typename ArgType>
void def_foo_overloads()
{
    def("foo", foo<ArgType>);
    // last type in list
}
template <typename ArgType, typename... MoreArgTypes>
void def_foo_overloads()
{
    def("foo", foo<ArgType>);
    def_foo_overloads(MoreArgTypes...);
}

// use it like:
def_foo_overloads<orignalFunctionNamespace::type1,
                  orignalFunctionNamespace::type2,
                  ...
                  orignalFunctionNamespace::typeN> ();

If you don't have access to the new standard, you can do the equivalent thing using the old recursive typelists.如果您无法访问新标准,则可以使用旧的递归类型列表来做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM