重载类成员函数标记为const

时间:2018-04-04 13:46:51

标签: c++ pybind11

我在重载标记为const的类成员函数时遇到问题,而当函数未标记为const时没有问题。此外,重载本身在纯C ++中也能正常工作。

以下失败

#include <vector>
#include <pybind11/pybind11.h>


class Foo
{
public:
  Foo(){};

  std::vector<double> bar(const std::vector<double> &a) const
  {
    return a;
  }

  std::vector<int> bar(const std::vector<int> &a) const
  {
    return a;
  }
};


namespace py = pybind11;

PYBIND11_MODULE(example,m)
{
  py::class_<Foo>(m, "Foo")
    .def("bar", py::overload_cast<const std::vector<double>&>(&Foo::bar));
}

使用编译:

clang++ -O3 -shared -std=c++14 `python3-config --cflags --ldflags --libs` example.cpp -o example.so -fPIC

给出错误:

...  
no matching function for call to object of type 'const detail::overload_cast_impl<const vector<double, allocator<double> > &>'
    .def("bar", py::overload_cast<const std::vector<double>&>(&Foo::bar));
...

当我删除函数的const标记时代码有效。

我应该如何执行此过载?

1 个答案:

答案 0 :(得分:2)

const重载方法有一个特殊标记。

namespace py = pybind11;

PYBIND11_MODULE(example,m)
{
  py::class_<Foo>(m, "Foo")
    .def("bar", py::overload_cast<const std::vector<double>&>(&Foo::bar, py::const_));
}