在Boost Python中需要命名参数

时间:2015-04-14 13:17:54

标签: c++ python-3.x boost-python

我正在尝试使Boost Python要求参数由调用者命名。

当Python 3实现PEP 3102时,我可以在纯Python中轻松完成:

def foo(*, name=None, age=None):
    print("%s is %d years" % (name, age))

以上意味着:

foo(name="Joe", age=33) # works
foo(age=33, name="Joe") # works
foo("Joe", 33) # raises TypeError

但是,这在Boost Python中并不简单。以下内容甚至没有结束:

#include <stdio.h>
#include <string>
#include <boost/python.hpp>
#include <boost/python/def.hpp>

void foo(const std::string& name, int age)
{
  printf("%s is %d years\n", name.c_str(), age);
}

BOOST_PYTHON_MODULE(hello)
{
  using namespace boost::python;
  def("foo", foo, (arg("name"), arg("age")));
}

虽然这适用于命名参数,但它们不是必需的,所以我仍然可以foo("Joe", 33)

我试过了:

  • 使用raw_function,但这要求我拥有(boost::python::tuple, boost::python::dict)的C ++签名。
  • (arg("*"), arg("name")="...", arg("age")=-1)公开函数,但不能编译。

是否有可能通过Boost Python公开foo,如顶级Python示例所述?

0 个答案:

没有答案