pybind / pybind/pybind11

[QUESTION] Register CRTP classes

Open
#3,026 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

I'm deriving a class using CRTP (as I have overloaded function that are templated), and I wanted to discuss if my solution is the best way to include the classes in the Python binding. Here is the minimal example I came up with:

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

namespace py = pybind11;

template <class Derived>
class BaseImpl
{
public:

    template <class T>
    T myfunc(const T& t)
    {
        return static_cast<Derived*>(this)->myfunc_impl(t);
    }

private:
    template <class T>
    T myfunc_impl(const T& t)
    {
        T ret = t;
        for (auto& i : ret) {
            i *= 2.0;
        }
        return ret;
    }
};

class Base : public BaseImpl<Base>
{
public:
    Base() = default;

private:
    friend class BaseImpl<Base>;
};

class Derived : public BaseImpl<Derived>
{
public:
    Derived() = default;

private:
    template <class T>
    T myfunc_impl(const T& t)
    {
        T ret = t;
        for (auto& i : ret) {
            i *= 3.0;
        }
        return ret;
    }

private:
    friend class BaseImpl<Derived>;
};

template <class T, class M>
auto registerBaseImpl(M& self)
{
    self.def(py::init<>())
        .def("myfunc", &T::template myfunc<std::vector<double>>);
}

PYBIND11_MODULE(mymodule, m)
{
    m.doc() = "CRTP example";

    py::class_<BaseImpl<Base>> BaseBase(m, "BaseBase");
    py::class_<BaseImpl<Derived>> BaseDerived(m, "BaseDerived");

    registerBaseImpl<BaseImpl<Base>>(BaseBase);
    registerBaseImpl<BaseImpl<Derived>>(BaseDerived);

    py::class_<Base, BaseImpl<Base>>(m, "Base")
        .def(py::init<>());

    py::class_<Derived, BaseImpl<Derived>>(m, "Derived")
        .def(py::init<>());
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal C++ example, the PYBIND11_MODULE entry point, registerBaseImpl, and the py::class_ declarations shown in the issue. Determine the supported approach for registering these CRTP classes; done means a clear recommendation or concrete scope, since no file or test is named.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.