Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload class member function marked const

Tags:

c++

pybind11

I am having trouble overloading class member functions that are marked const, while there is no problem when the functions are not marked const. Also the overload itself works fine in pure C++.

The following fails

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

Compiled using:

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

Gives error:

...  
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));
...

Whereas the code works when I remove the const mark of the functions.

How should I perform this overload?

like image 599
Tom de Geus Avatar asked Oct 14 '25 03:10

Tom de Geus


1 Answers

There is a special tag for const overloaded methods.

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_));
}
like image 175
273K Avatar answered Oct 17 '25 03:10

273K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!