重载类标记为 const 的成员函数

Tom*_*eus 2 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));
}
Run Code Online (Sandbox Code Playgroud)

编译使用:

clang++ -O3 -shared -std=c++14 `python3-config --cflags --ldflags --libs` example.cpp -o example.so -fPIC
Run Code Online (Sandbox Code Playgroud)

给出错误:

...  
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));
...
Run Code Online (Sandbox Code Playgroud)

const而当我删除函数的标记时,代码就可以工作了。

我应该如何执行此超载?

S.M*_*.M. 7

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_));
}
Run Code Online (Sandbox Code Playgroud)