我现在正在查看来自 CARLA 模拟器 ( http://carla.org/ ) 的一些代码。
它使用 boost python 向 python 公开了许多 C++ 类和成员函数。但我无法理解下面几行的语法..
void export_blueprint() {
using namespace boost::python;
namespace cc = carla::client;
namespace crpc = carla::rpc;
...
class_<cc::ActorBlueprint>("ActorBlueprint", no_init)
.add_property("id", +[](const cc::ActorBlueprint &self) -> std::string {
return self.GetId();
})
.add_property("tags", &cc::ActorBlueprint::GetTags)
.def("contains_tag", &cc::ActorBlueprint::ContainsTag)
.def("match_tags", &cc::ActorBlueprint::MatchTags)
.def("contains_attribute", &cc::ActorBlueprint::ContainsAttribute)
.def("get_attribute", +[](const cc::ActorBlueprint &self, const std::string &id) -> cc::ActorAttribute {
return self.GetAttribute(id);
}) // <=== THESE LINES
.def("set_attribute", &cc::ActorBlueprint::SetAttribute)
.def("__len__", &cc::ActorBlueprint::size)
.def("__iter__", range(&cc::ActorBlueprint::begin, &cc::ActorBlueprint::end))
.def(self_ns::str(self_ns::self))
;
}
下面的代码是什么
.def("get_attribute", +[](const cc::ActorBlueprint &self,
const std::string &id) -> cc::ActorAttribute {
return self.GetAttribute(id);
})
吝啬的?看起来 python 类 ActorBlueprint 的函数 get_attribute 函数正在被新(覆盖)定义为从 python 接口传递的新参数。我几乎可以肯定,但是否有任何关于此语法的文档?我在https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/tutorial/index.html 中找不到一个。
我将逐个解释它。
.def("get_attribute", ...) //method call with arguments
+[](const cc::ActorBlueprint &self, const std::string &id) -> cc::ActorAttribute {...}
// C++ lambda, passed to above method as second argument
return self.GetAttribute(id); // this is the lambda body
您可以在此处阅读有关 lambda 语法的信息。此外,+
在 lambda 前面的内容对您来说可能看起来很奇怪。它用于触发到普通旧函数指针的转换。在这里阅读。
lambda 中的那个箭头-> cc::ActorAttribute
指定了返回类型。它也可以用于普通的函数和方法。
这是本机 C++ 语法,而不是特定于 boost 的东西。
作为这段代码的结果,python 类ActorBlueprint
的方法get_attribute
将被定义。它将有一个字符串参数,并将执行 lambda 主体所做的操作(在这种情况下按 id 返回属性)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句