'How to correctly bind C++ clone pattern with pybind11?

I'm attempting to wrap a C++ class implementing the clone pattern with pybind11. I've been following the documentation provided (see https://pybind11.readthedocs.io/en/stable/advanced/classes.html) but whenever I try to compile the code below, the compiler throws an error:

pybind11\include\pybind11\cast.h(1031,12): error C2672: 'cast_op': no matching overloaded function found [...]
pybind11\include\pybind11\cast.h(1105): message : see reference to function template instantiation 'T pybind11::cast<T,0>(const pybind11::handle &)' being compiled [...]
with
[
   T=std::unique_ptr<Base,std::default_delete<Base>>
]
pybind11\include\pybind11\cast.h(1168): message : see reference to function template instantiation 'std::unique_ptr<Base,std::default_delete<Base>> pybind11::cast<T>(pybind11::object &&)' being compiled [...]
with
[
   T=std::unique_ptr<Base,std::default_delete<Base>>
]

Code:

#include <pybind11/pybind11.h>

#include <memory>

class Base
{
public:
    Base()
    {
    }

    virtual std::unique_ptr<Base> Clone() const
    {
        return std::make_unique<Base>(*this);
    }
};

class PyBase : public Base
{
public:
    using Base::Base;

    virtual std::unique_ptr<Base> Clone() const
    {
        PYBIND11_OVERRIDE_NAME(std::unique_ptr<Base>, Base, "clone", Clone);
    }
};

PYBIND11_MODULE(example, module)
{
    pybind11::class_<Base, PyBase>(module, "Base")
        .def(pybind11::init<>())
        .def("clone", &Base::Clone);
}

How do I correctly bind this code with pybind11?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source