超载类成员功能标记为const

Overload class member function marked const

本文关键字:记为 const 功能 成员 超载      更新时间:2023-10-16

我在标记为 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标记时,代码可以工作。

我应该如何执行此超载?

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_));
}