Skip to content

Commit 6b52c83

Browse files
committed
Allow passing base types as a template parameter
This allows a slightly cleaner base type specification of: py::class_<Type, Base>("Type") as an alternative to py::class_<Type>("Type", py::base<Base>()) As with the other template parameters, the order relative to the holder or trampoline types doesn't matter. This also includes a compile-time assertion failure if attempting to specify more than one base class (but is easily extendible to support multiple inheritance, someday, by updating the class_selector::set_bases function to set multiple bases).
1 parent 5fffe20 commit 6b52c83

9 files changed

+76
-40
lines changed

docs/advanced.rst

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1227,7 +1227,7 @@ section.
12271227
the other existing exception translators.
12281228

12291229
The ``py::exception`` wrapper for creating custom exceptions cannot (yet)
1230-
be used as a ``py::base``.
1230+
be used as a base type.
12311231

12321232
.. _eigen:
12331233

@@ -1811,16 +1811,17 @@ However, it can be acquired as follows:
18111811
.def(py::init<const std::string &>())
18121812
.def("bark", &Dog::bark);
18131813
1814-
Alternatively, we can rely on the ``base`` tag, which performs an automated
1815-
lookup of the corresponding Python type. However, this also requires invoking
1816-
the ``import`` function once to ensure that the pybind11 binding code of the
1817-
module ``basic`` has been executed.
1814+
Alternatively, you can specify the base class as a template parameter option to
1815+
``class_``, which performs an automated lookup of the corresponding Python
1816+
type. Like the above code, however, this also requires invoking the ``import``
1817+
function once to ensure that the pybind11 binding code of the module ``basic``
1818+
has been executed:
18181819

18191820
.. code-block:: cpp
18201821
18211822
py::module::import("basic");
18221823
1823-
py::class_<Dog>(m, "Dog", py::base<Pet>())
1824+
py::class_<Dog, Pet>(m, "Dog")
18241825
.def(py::init<const std::string &>())
18251826
.def("bark", &Dog::bark);
18261827

docs/classes.rst

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,16 +185,23 @@ inheritance relationship:
185185
std::string bark() const { return "woof!"; }
186186
};
187187
188-
There are two different ways of indicating a hierarchical relationship to
189-
pybind11: the first is by specifying the C++ base class explicitly during
190-
construction using the ``base`` attribute:
188+
There are three different ways of indicating a hierarchical relationship to
189+
pybind11: the first specifies the C++ base class as an extra template
190+
parameter of the :class:`class_`; the second uses a special ``base`` attribute
191+
passed into the constructor:
191192

192193
.. code-block:: cpp
193194
194195
py::class_<Pet>(m, "Pet")
195196
.def(py::init<const std::string &>())
196197
.def_readwrite("name", &Pet::name);
197198
199+
// Method 1: template parameter:
200+
py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
201+
.def(py::init<const std::string &>())
202+
.def("bark", &Dog::bark);
203+
204+
// Method 2: py::base attribute:
198205
py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
199206
.def(py::init<const std::string &>())
200207
.def("bark", &Dog::bark);
@@ -208,11 +215,12 @@ Alternatively, we can also assign a name to the previously bound ``Pet``
208215
pet.def(py::init<const std::string &>())
209216
.def_readwrite("name", &Pet::name);
210217
218+
// Method 3: pass parent class_ object:
211219
py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
212220
.def(py::init<const std::string &>())
213221
.def("bark", &Dog::bark);
214222
215-
Functionality-wise, both approaches are completely equivalent. Afterwards,
223+
Functionality-wise, all three approaches are completely equivalent. Afterwards,
216224
instances will expose fields and methods of both types:
217225

218226
.. code-block:: pycon

include/pybind11/cast.h

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -798,12 +798,12 @@ template <typename type, typename holder_type> class type_caster_holder : public
798798
holder_type holder;
799799
};
800800

801+
// PYBIND11_DECLARE_HOLDER_TYPE holder types:
801802
template <typename base, typename holder> struct is_holder_type :
802-
// PYBIND11_DECLARE_HOLDER_TYPE holder types:
803-
std::conditional<std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>>::value,
804-
std::true_type,
805-
std::false_type>::type {};
806-
template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
803+
std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
804+
// Specialization for always-supported unique_ptr holders:
805+
template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
806+
std::true_type {};
807807

808808
template <typename T> struct handle_type_name { static PYBIND11_DESCR name() { return _<T>(); } };
809809
template <> struct handle_type_name<bytes> { static PYBIND11_DESCR name() { return _(PYBIND11_BYTES_NAME); } };

include/pybind11/common.h

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -358,20 +358,20 @@ template <template<typename> class P, typename T, typename... Ts>
358358
struct any_of_t<P, T, Ts...> : conditional_t<P<T>::value, std::true_type, any_of_t<P, Ts...>> { };
359359
#endif
360360

361-
// Extracts the first type from the template parameter pack matching the predicate, or void if none match.
362-
template <template<class> class Predicate, class... Ts> struct first_of;
363-
template <template<class> class Predicate> struct first_of<Predicate> {
364-
using type = void;
361+
// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
362+
template <template<class> class Predicate, class Default, class... Ts> struct first_of;
363+
template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
364+
using type = Default;
365365
};
366-
template <template<class> class Predicate, class T, class... Ts>
367-
struct first_of<Predicate, T, Ts...> {
366+
template <template<class> class Predicate, class Default, class T, class... Ts>
367+
struct first_of<Predicate, Default, T, Ts...> {
368368
using type = typename std::conditional<
369369
Predicate<T>::value,
370370
T,
371-
typename first_of<Predicate, Ts...>::type
371+
typename first_of<Predicate, Default, Ts...>::type
372372
>::type;
373373
};
374-
template <template<class> class Predicate, class... T> using first_of_t = typename first_of<Predicate, T...>::type;
374+
template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
375375

376376
// Counts the number of types in the template parameter pack matching the predicate
377377
template <template<typename> class Predicate, typename... Ts> struct count_t;

include/pybind11/pybind11.h

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -802,34 +802,47 @@ class generic_type : public object {
802802

803803
static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
804804
};
805+
806+
template <template<typename> class Predicate, typename... BaseTypes> struct class_selector;
807+
template <template<typename> class Predicate, typename Base, typename... Bases>
808+
struct class_selector<Predicate, Base, Bases...> {
809+
static inline void set_bases(detail::type_record &record) {
810+
if (Predicate<Base>::value) record.base_type = &typeid(Base);
811+
else class_selector<Predicate, Bases...>::set_bases(record);
812+
}
813+
};
814+
template <template<typename> class Predicate>
815+
struct class_selector<Predicate> {
816+
static inline void set_bases(detail::type_record &) {}
817+
};
818+
805819
NAMESPACE_END(detail)
806820

807821
template <typename type_, typename... options>
808822
class class_ : public detail::generic_type {
809823
template <typename T> using is_holder = detail::is_holder_type<type_, T>;
810824
template <typename T> using is_subtype = detail::bool_constant<std::is_base_of<type_, T>::value && !std::is_same<T, type_>::value>;
825+
template <typename T> using is_base_class = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>;
811826
template <typename T> using is_valid_class_option =
812827
detail::bool_constant<
813828
is_holder<T>::value ||
814-
is_subtype<T>::value
829+
is_subtype<T>::value ||
830+
is_base_class<T>::value
815831
>;
816832

817-
using extracted_holder_t = typename detail::first_of_t<is_holder, options...>;
818-
819833
public:
820834
using type = type_;
821-
using type_alias = detail::first_of_t<is_subtype, options...>;
835+
using type_alias = detail::first_of_t<is_subtype, void, options...>;
822836
constexpr static bool has_alias = !std::is_void<type_alias>::value;
823-
using holder_type = typename std::conditional<
824-
std::is_void<extracted_holder_t>::value,
825-
std::unique_ptr<type>,
826-
extracted_holder_t
827-
>::type;
837+
using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
828838
using instance_type = detail::instance<type, holder_type>;
829839

830840
static_assert(detail::all_of_t<is_valid_class_option, options...>::value,
831841
"Unknown/invalid class_ template parameters provided");
832842

843+
static_assert(detail::count_t<is_base_class, options...>::value <= 1,
844+
"Invalid class_ base types: multiple inheritance is not supported");
845+
833846
PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
834847

835848
template <typename... Extra>
@@ -843,6 +856,8 @@ class class_ : public detail::generic_type {
843856
record.init_holder = init_holder;
844857
record.dealloc = dealloc;
845858

859+
detail::class_selector<is_base_class, options...>::set_bases(record);
860+
846861
/* Process optional arguments, if any */
847862
detail::process_attributes<Extra...>::init(extra..., &record);
848863

tests/test_inheritance.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ class Rabbit : public Pet {
3131
Rabbit(const std::string &name) : Pet(name, "parrot") {}
3232
};
3333

34+
class Hamster : public Pet {
35+
public:
36+
Hamster(const std::string &name) : Pet(name, "rodent") {}
37+
};
38+
3439
std::string pet_name_species(const Pet &pet) {
3540
return pet.name() + " is a " + pet.species();
3641
}
@@ -59,6 +64,10 @@ test_initializer inheritance([](py::module &m) {
5964
py::class_<Rabbit>(m, "Rabbit", py::base<Pet>())
6065
.def(py::init<std::string>());
6166

67+
/* And another: list parent in class template arguments */
68+
py::class_<Hamster, Pet>(m, "Hamster")
69+
.def(py::init<std::string>());
70+
6271
m.def("pet_name_species", pet_name_species);
6372
m.def("dog_bark", dog_bark);
6473

tests/test_inheritance.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33

44
def test_inheritance(msg):
5-
from pybind11_tests import Pet, Dog, Rabbit, dog_bark, pet_name_species
5+
from pybind11_tests import Pet, Dog, Rabbit, Hamster, dog_bark, pet_name_species
66

77
roger = Rabbit('Rabbit')
88
assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
@@ -16,6 +16,9 @@ def test_inheritance(msg):
1616
assert molly.name() + " is a " + molly.species() == "Molly is a dog"
1717
assert pet_name_species(molly) == "Molly is a dog"
1818

19+
fred = Hamster('Fred')
20+
assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
21+
1922
assert dog_bark(molly) == "Woof!"
2023

2124
with pytest.raises(TypeError) as excinfo:

tests/test_issues.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ void init_issues(py::module &m) {
9696

9797
py::class_<ElementBase, std::shared_ptr<ElementBase>> (m2, "ElementBase");
9898

99-
py::class_<ElementA, std::shared_ptr<ElementA>>(m2, "ElementA", py::base<ElementBase>())
99+
py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m2, "ElementA")
100100
.def(py::init<int>())
101101
.def("value", &ElementA::value);
102102

tests/test_virtual_functions.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -258,12 +258,12 @@ void initialize_inherited_virtuals(py::module &m) {
258258
.def("unlucky_number", &A_Repeat::unlucky_number)
259259
.def("say_something", &A_Repeat::say_something)
260260
.def("say_everything", &A_Repeat::say_everything);
261-
py::class_<B_Repeat, PyB_Repeat>(m, "B_Repeat", py::base<A_Repeat>())
261+
py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, "B_Repeat")
262262
.def(py::init<>())
263263
.def("lucky_number", &B_Repeat::lucky_number);
264-
py::class_<C_Repeat, PyC_Repeat>(m, "C_Repeat", py::base<B_Repeat>())
264+
py::class_<C_Repeat, B_Repeat, PyC_Repeat>(m, "C_Repeat")
265265
.def(py::init<>());
266-
py::class_<D_Repeat, PyD_Repeat>(m, "D_Repeat", py::base<C_Repeat>())
266+
py::class_<D_Repeat, C_Repeat, PyD_Repeat>(m, "D_Repeat")
267267
.def(py::init<>());
268268

269269
// Method 2: Templated trampolines
@@ -272,12 +272,12 @@ void initialize_inherited_virtuals(py::module &m) {
272272
.def("unlucky_number", &A_Tpl::unlucky_number)
273273
.def("say_something", &A_Tpl::say_something)
274274
.def("say_everything", &A_Tpl::say_everything);
275-
py::class_<B_Tpl, PyB_Tpl<>>(m, "B_Tpl", py::base<A_Tpl>())
275+
py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, "B_Tpl")
276276
.def(py::init<>())
277277
.def("lucky_number", &B_Tpl::lucky_number);
278-
py::class_<C_Tpl, PyB_Tpl<C_Tpl>>(m, "C_Tpl", py::base<B_Tpl>())
278+
py::class_<C_Tpl, B_Tpl, PyB_Tpl<C_Tpl>>(m, "C_Tpl")
279279
.def(py::init<>());
280-
py::class_<D_Tpl, PyB_Tpl<D_Tpl>>(m, "D_Tpl", py::base<C_Tpl>())
280+
py::class_<D_Tpl, C_Tpl, PyB_Tpl<D_Tpl>>(m, "D_Tpl")
281281
.def(py::init<>());
282282

283283
};

0 commit comments

Comments
 (0)