【问题标题】:Export functions which returns a reference导出返回引用的函数
【发布时间】:2011-03-20 14:42:35
【问题描述】:

我想导出到python模块(用c++编写,带有boost.python库)这样的功能:

Vec2<Type> &normalize () 
Type dot(const Vec2<Type> &vector) const

这些是模板类Vec2 的成员。这是我的导出代码:

bp::class_< Vec2<int> >("Vec2i", bp::init<int, int>())
    .def("Length", &Vec2<int>::length)
    .def("Dot", &Vec2<int>::dot, bp::return_internal_reference<>());
    //.def("Normalize", &Vec2<int>::normalize);

Length 方法编译成功,但DotNormalize 返回相同的错误(编译期间):

 error: no matching function for call to ‘boost::python::class_<Vec2<int> >::def(const char [4], <unresolved overloaded function type>, boost::python::return_internal_reference<>)’

我做错了什么?


UPD

真正的类名是:CL_Vec&lt;Type&gt;,这里是docs

【问题讨论】:

  • 由于这些显然是成员函数,请显示整个类定义。
  • 是否还有额外的dot 过载而您没有向我们展示?
  • @larsmans @john-zwinck 我已添加到帖子中。

标签: c++ python boost reference export


【解决方案1】:

如果您查看vec2.h(或您链接到的文档),您会发现dotnormalize 都超载,因为还存在static 版本。

您可以通过使用一些函数指针来解决这个问题:

Vec2<int> &(Vec2<int>::*norm)() = &Vec2<int>::normalize;

然后在def 中使用它,如here 所述。

【讨论】:

  • @Ockonal:dotconst方法,必须反映在函数指针的类型中。
  • 谢谢。抱歉,我了解我的问题。
  • @Ockonal:不用道歉!
【解决方案2】:

当编译器说:

<unresolved overloaded function type>

查看指向成员的指针或函数指针 (&Vec2::dot),看看它是否引用了一组重载函数(应该如此)。在这种情况下,您可能需要显式 static_cast 指向特定的成员指针或函数指针类型,包括函数参数类型。

【讨论】:

  • 查看文档,normalize 和 dot 还有另一个函数——尽管它们都是静态的。
  • 有趣...因为 &CLASS::FUNCTION 语法对静态也有效(尽管它使 & 变得不必要,因此我喜欢在我的代码中省略它),编译器可以' t告诉你想要哪一个。即使它实际上不是指向成员的指针,也适用相同的原则。
猜你喜欢
  • 2022-11-24
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
相关资源
最近更新 更多