Skip to content

Commit b4e1ab8

Browse files
Docs: Demonstrate non-enum internal types in example (#3314)
* Docs: Demonstrate non-enum internal types in example Previously example only demonstrated internal enumeration type. To show that it works for other internal types the same way the example was updated with an additional struct Pet::Attributes type. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent a1830d5 commit b4e1ab8

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

docs/classes.rst

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -446,8 +446,7 @@ you can use ``py::detail::overload_cast_impl`` with an additional set of parenth
446446
Enumerations and internal types
447447
===============================
448448

449-
Let's now suppose that the example class contains an internal enumeration type,
450-
e.g.:
449+
Let's now suppose that the example class contains internal types like enumerations, e.g.:
451450

452451
.. code-block:: cpp
453452
@@ -457,10 +456,15 @@ e.g.:
457456
Cat
458457
};
459458
459+
struct Attributes {
460+
float age = 0;
461+
};
462+
460463
Pet(const std::string &name, Kind type) : name(name), type(type) { }
461464
462465
std::string name;
463466
Kind type;
467+
Attributes attr;
464468
};
465469
466470
The binding code for this example looks as follows:
@@ -471,15 +475,21 @@ The binding code for this example looks as follows:
471475
472476
pet.def(py::init<const std::string &, Pet::Kind>())
473477
.def_readwrite("name", &Pet::name)
474-
.def_readwrite("type", &Pet::type);
478+
.def_readwrite("type", &Pet::type)
479+
.def_readwrite("attr", &Pet::attr);
475480
476481
py::enum_<Pet::Kind>(pet, "Kind")
477482
.value("Dog", Pet::Kind::Dog)
478483
.value("Cat", Pet::Kind::Cat)
479484
.export_values();
480485
481-
To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
482-
``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
486+
py::class_<Pet::Attributes> attributes(pet, "Attributes")
487+
.def(py::init<>())
488+
.def_readwrite("age", &Pet::Attributes::age);
489+
490+
491+
To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
492+
``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
483493
constructor. The :func:`enum_::export_values` function exports the enum entries
484494
into the parent scope, which should be skipped for newer C++11-style strongly
485495
typed enums.

0 commit comments

Comments
 (0)