docs: the order of alternatives for variant types matters, and follows the same rules as overload resolution (#2784)

This commit is contained in:
Yannick Jadoul 2021-01-14 05:17:27 +01:00 committed by GitHub
parent 40931961e3
commit 1faf4a8ae4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 0 deletions

View File

@ -72,6 +72,17 @@ The ``visit_helper`` specialization is not required if your ``name::variant`` pr
a ``name::visit()`` function. For any other function name, the specialization must be a ``name::visit()`` function. For any other function name, the specialization must be
included to tell pybind11 how to visit the variant. included to tell pybind11 how to visit the variant.
.. warning::
When converting a ``variant`` type, pybind11 follows the same rules as when
determining which function overload to call (:ref:`overload_resolution`), and
so the same caveats hold. In particular, the order in which the ``variant``'s
alternatives are listed is important, since pybind11 will try conversions in
this order. This means that, for example, when converting ``variant<int, bool>``,
the ``bool`` variant will never be selected, as any Python ``bool`` is already
an ``int`` and is convertible to a C++ ``int``. Changing the order of alternatives
(and using ``variant<bool, int>``, in this example) provides a solution.
.. note:: .. note::
pybind11 only supports the modern implementation of ``boost::variant`` pybind11 only supports the modern implementation of ``boost::variant``

View File

@ -524,6 +524,8 @@ The default behaviour when the tag is unspecified is to allow ``None``.
not allow ``None`` as argument. To pass optional argument of these copied types consider not allow ``None`` as argument. To pass optional argument of these copied types consider
using ``std::optional<T>`` using ``std::optional<T>``
.. _overload_resolution:
Overload resolution order Overload resolution order
========================= =========================